# -*- coding: utf-8 -*-
# @Time       : 2019/7/27 下午4:47
# @Author     : Simon
# @Email      : 
# @File       : func.py
# @Software   : PyCharm
# @Description:
from copy import deepcopy

import demjson
import emoji

from config import config
from spider import ELESpider, MTSpider


from .model import *
from .bidding import *
from decimal import Decimal
import time
import json, hashlib, math
import hashlib


class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)


def IsInAdTime(shiptime, ct, cDay):
    '''
    判断是否在营业时间
    :param shiptime:
    :return:
    '''

    try:
        shipTimes = eval(shiptime)
    except:
        shipTimes = shiptime
    # if not shiptime and not ad:return True
    # if not shiptime and ad:return False

    for shiptime in shipTimes:
        starttime = shiptime.get("s")
        endtime = shiptime.get("e")
        if starttime and endtime:
            st = cDay + ' ' + starttime + ':00'
            et = cDay + ' ' + endtime + ':00'
            if ct >= st and ct <= et:
                return True

    return False


def checkUser(username, pwd):
    '''
    检查登录用户
    :param username:
    :param pwd:
    :return:
    '''
    try:
        session = Session()
        user = session.query(User.username, User.password, User.realname, User.salt, User.expiretime).filter(
            User.username == username, User.deleted == 0).first()
        session.close()
        if not user:
            return {"code": config.FAIL_USER, "realname": ""}
        u, p, realname, salt, expiretime = user
        # logger.info(pwd)
        logger.info(salt)
        pwdmd5 = hashlib.md5((str(pwd) + str(salt)).encode(encoding='UTF-8')).hexdigest()
        logger.info(pwdmd5)
        logger.info(p)
        if expiretime < int(time.time()):
            return {"code": config.FAIL_EXPIRE, "realname": ""}
        elif p == pwdmd5:
            return {"code": config.SUCCESS, "realname": realname, "salt": pwdmd5}
        else:
            return {"code": config.FAIL_PWD, "realname": ""}
    except:
        logger.warning(traceback.format_exc())
        return {"code": config.PENNDING_ERROR, "realname": ""}

def getShopOrder(sid):
    today = datetime.datetime.now().strftime("%Y-%m-%d")
    firstDay = (datetime.datetime.now() + datetime.timedelta(days=-8)).strftime("%Y-%m-%d")
    session = Session()
    account, type = getAccountById(sid)
    orders = {}
    orderList = session.query(YesOrderInfo).filter(YesOrderInfo.account == account,
                                                   YesOrderInfo.day > firstDay).order_by(YesOrderInfo.day).all()
    dayTime = []
    for i in range(-7, 0):
        day = (datetime.datetime.now() + datetime.timedelta(days = i)).strftime("%Y-%m-%d")
        orderList = session.query(YesOrderInfo).filter(YesOrderInfo.account == account,
                                                       YesOrderInfo.day == day).first()
        dayTime.append(day)
        if orderList:
            if orderList.InfoList:
                orders["day" + str(i + 8)] = {"infoList": eval(orderList.InfoList), "null": 0}
            else:
                orders["day" + str(i + 8)] = {"infoList": [], "null": 1}
        else:
            orders["day" + str(i + 8)] = {"infoList": [], "null": 1}
    orders['dayTime'] = dayTime
    return orders




def getCurrentOrder(sid, index):
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == sid).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == sid).first()
    day = (datetime.datetime.now() + datetime.timedelta(days=int(index) - 8)).strftime("%Y-%m-%d")
    ct = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:00")
    account = None
    if mt:
        cookies = mt.cookies
        account = mt.account
        mtSpider = MTSpider(cookies)
        try:
            yestodayNum = mtSpider.getCurrentOrder(day)
            if len(yestodayNum) != 0:
                timelst = []
                for order in yestodayNum:
                    timelst.append(order.split(' ')[1])
                timelst.sort()
                dayperiod = {}
                i = 0
                j = 30
                index = 0
                while i < 24:
                    while j <= 60:
                        if j == 60:
                            j = 0
                            break
                        else:
                            t = "%02d:%02d:00" % (i, j)
                            dayperiod[t] = 0
                            while index < len(timelst) and timelst[index] < t:
                                dayperiod[t] = dayperiod[t] + 1
                                index += 1
                            j += 30
                    i += 1
                dayperiod["23:59:59"] = 0

                orderList = []  # 目前orderlist是96个
                for key, value in dayperiod.items():
                    orderList.append(value)
                updYseOrderInfo(account, str(orderList), day, ct)
                return orderList
            else:
                return False
        except:
            return False
    elif ele:
        cookies = ele.cookies
        account = ele.account
        eleSpider = ELESpider(cookies)
        daysNum = eleSpider.getAllOrder(day + "T00:00:00", day + "T23:59:59", 200)
        timelst = []
        # 所有下单时间存进列表
        if daysNum:
            for dayNum in daysNum:
                # 2019-10-01T21:22:09,返回的时间是这样的，只取21:22:09
                timelst.append(dayNum.get("activeTime").split('T')[1])
            timelst.sort()
            dayperiod = {}
            i = 0
            j = 30
            index = 0
            while i < 24:
                while j <= 60:
                    if j == 60:
                        j = 0
                        break
                    else:
                        t = "%02d:%02d:00" % (i, j)
                        dayperiod[t] = 0
                        while index < len(timelst) and timelst[index] < t:
                            dayperiod[t] = dayperiod[t] + 1
                            index += 1
                        j += 30
                i += 1
            dayperiod["23:59:59"] = 0
            orderList = []  # 目前orderlist是96个
            for key, value in dayperiod.items():
                orderList.append(value)
            updYseOrderInfo(account, str(orderList), day, ct)
            return orderList
        else:
            return False


def getMtShops():
    session = Session()
    try:
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.deleted == 0).all()
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.deleted == 0).all()
    except:
        logger.info("获取店铺列表失败")
        logger.info(traceback.format_exc())
        session.close()
        return [[], []]

    session.close()
    shop_list = []
    shop_ele = []
    shop_mt = []
    for s in ele:
        # isEnable为1,不在推广事件内
        wait = 0
        isEnable = 0
        guard = 0
        if s.isenable == 1:
            if not IsInShopAdTime(s.adTime):
                wait = 1
                isEnable = 0
                guard = 0
        if IsInShopAdTime(s.adTime):
            if s.guard == 1:
                guard = 1
                isEnable = 0
                wait = 0

        if s.isenable == 1 and s.guard != 1 and IsInShopAdTime(s.adTime):
            isEnable = 1
            wait = 0
            guard = 0
        shop = dict(
            id=s.eleId,
            isEnable=isEnable,
            shoptype=2,
            guard=guard,
            waitBidding=wait,
            name=s.eleName,
            account = s.account,
        )
        shop_ele.append(shop)
    ##把正在推广的店放在最前面
    eleShops = []
    for ele in shop_ele:
        if ele.get("isEnable") == 1:
            eleShops.insert(0, ele)
        else:
            eleShops.append(ele)
    for s in mt:
        wait = 0
        isEnable = 0
        guard = 0
        if s.isenable == 1:
            if not IsInShopAdTime(s.adTime):
                wait = 1
                isEnable = 0
                guard = 0
        if IsInShopAdTime(s.adTime):
            if s.guard == 1:
                guard = 1
                isEnable = 0
                wait = 0

        if s.isenable == 1 and s.guard != 1 and IsInShopAdTime(s.adTime):
            isEnable = 1
            wait = 0
            guard = 0
        shop = dict(
            id=s.mtId,
            isEnable=isEnable,
            shoptype=1,
            guard=guard,
            waitBidding=wait,
            name=s.mtName,
            account=s.account,
        )
        shop_mt.append(shop)
    mtShops = []
    for mt in shop_mt:
        if mt.get("isEnable") == 1:
            mtShops.insert(0, mt)
        else:
            mtShops.append(mt)
    shop_list.append(mtShops)
    shop_list.append(eleShops)
    return shop_list


def getShopPeriodCurbid(shopId, shopType, date):
    biddingInfo = getPriceCount(shopId, shopType, date + " 00:00:00")
    avgPrice = biddingInfo.get("masterData", {}).get("avgPrice")
    if sum(avgPrice) == 0 or not avgPrice:
        return 1000
    else:
        return avgPrice


def IsInShopAdTime(shiptime):
    if not shiptime:
        return False
    try:
        shipTimes = eval(shiptime)
    except:
        shipTimes = shiptime
    if not shipTimes:
        return False
    for shiptime in shipTimes:
        starttime = shiptime.get("s")
        endtime = shiptime.get("e")
        if starttime and endtime:
            st = datetime.datetime.now().date().strftime("%Y-%m-%d") + ' ' + starttime
            et = datetime.datetime.now().date().strftime("%Y-%m-%d") + ' ' + endtime
            if datetime.datetime.now().strftime("%Y-%m-%d %H:%M") >= st and datetime.datetime.now().strftime(
                    "%Y-%m-%d %H:%M") <= et:
                return True

    return False


def newGetPriceCount(sid, shopType, date, app=0):
    '''
    获取前端主模块的数据
    :param sid: 真实的shopId
    :param shopType: 店铺种类
    :param date: 获取什么时间的数据
    :return:
    '''
    if date:
        today = date
    else:
        todayDateTime = datetime.datetime.now()
        today = todayDateTime.strftime("%Y-%m-%d 00:00:00")
    todayPlus = (datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
        "%Y-%m-%d %H:%M:%S")
    session = Session()
    logs = session.query(ShopBidding).filter(ShopBidding.shopid == sid, ShopBidding.biddingTime >= today,
                                             ShopBidding.biddingTime <= todayPlus).all()
    shopInfo = getShopsInfo(sid, shopType)
    specialTime = shopInfo.get("specialTime", "")
    adTime = shopInfo.get("adTime", "")
    session.close()
    # 判断忙时的时间段
    try:
        specialTime = eval(specialTime)
        adTime = eval(adTime)
    except:
        specialTime = specialTime
        adTime = adTime
    # 所有的时间段
    item2 = []
    today = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S")
    todayTime = today.strftime("%Y-%m-%d")
    nowTime = todayTime + " " + datetime.datetime.now().strftime("%H:%M:%S")
    for i in range(144):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=10)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)
    busyTime = []
    for sTime in specialTime:
        if sTime.get("type") == 1:
            startTime = todayTime + " " + sTime['s'] + ":00"
            endTime = todayTime + " " + sTime['e'] + ":00"
            for item in item2:
                if startTime <= item[1] and item[1] < endTime:
                    busyTime.append(item[1])
    realPeriodExposure = {}
    priceCount = {}
    priceDict = {}
    realTimeOrder = {}
    for item in item2:
        priceDict[item[1]] = {}
        realPeriodExposure[item[1]] = 0
        realTimeOrder[item[1]] = 0
        if not date:
            if item[0] < nowTime <= item[1]:
                break
    for i in range(len(logs) - 1):
        if i == 0:
            periodOrder = int(logs[i].realTimeOrder)
        else:
            periodOrder = int(logs[i + 1].realTimeOrder) - int(logs[i].realTimeOrder)
        periodExposure = int(logs[i + 1].exposureNum) - int(logs[i].exposureNum)
        for item in item2:
            if logs[i + 1].biddingTime > item[0] and logs[i + 1].biddingTime <= item[1]:
                if item[1] in priceDict.keys():
                    realPeriodExposure[item[1]] += periodExposure
                    realTimeOrder[item[1]] += periodOrder
                    if float(logs[i].basePrice) in priceDict[item[1]].keys():
                        priceDict[item[1]][float(logs[i].basePrice)] += periodExposure
                    else:
                        priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                else:
                    realTimeOrder[item[1]] = periodOrder
                    realPeriodExposure[item[1]] = periodExposure
                    priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                break
        if not float(logs[i].basePrice) in priceCount.keys():
            priceCount[float(logs[i].basePrice)] = periodExposure
        else:
            priceCount[float(logs[i].basePrice)] = priceCount[float(logs[i].basePrice)] + periodExposure
    # 全天的分布
    priceCount = sorted(priceCount.items(), key=lambda x: x[0])
    # 每半小时的分布
    orderCounts = []
    price = []
    count = []
    temp = {}
    for t in priceCount:
        price.append(t[0])
        count.append(t[1])
    orderCounts.append(price)
    orderCounts.append(count)
    maxPrice = []
    minPrice = []
    avgPrice = []
    hourPriceCounts = {}
    realTimeOrderList = []
    for kDict, vDict in priceDict.items():
        if vDict == {}:
            maxPrice.append(0)
            minPrice.append(0)
            avgPrice.append(0)
            hourPriceCounts[kDict] = None
        else:
            pDict = sorted(vDict.items(), key=lambda x: x[0])
            minPrice.append(pDict[0][0])
            maxPrice.append(pDict[-1][0])
            allNum = 0
            exposure = 0
            price = []
            priceNum = []
            for t in pDict:
                t = list(t)
                if t[1] == 0:
                    t[1] = 1
                allNum += t[0] * t[1]
                exposure += t[1]
                price.append(t[0])
                priceNum.append(t[1])
            if int(exposure) == 0:
                exposure = 1
                allNum = 0.1
            avgPrice.append(round(allNum / exposure, 2))
            hourPriceCounts[kDict] = {"price": price, "priceNum": priceNum}
    periodExposure = []
    for k, v in realPeriodExposure.items():
        periodExposure.append(v)
    for k, v in realTimeOrder.items():
        realTimeOrderList.append(v)
    masterData = {"maxPrice": maxPrice, "minPrice": minPrice, "avgPrice": avgPrice}
    item = {"hourPriceCounts": hourPriceCounts, "allDayPriceCounts": orderCounts, "masterData": masterData,
            "periodExposure": periodExposure,
            "realTimeOrderList": realTimeOrderList, "busyTime": busyTime}
    return item


def getAppPriceCount(sid, shopType, date, app=0):
    '''
    获取前端主模块的数据
    :param sid: 真实的shopId
    :param shopType: 店铺种类
    :param date: 获取什么时间的数据
    :return:
    '''
    today = date
    todayPlus = (datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
        "%Y-%m-%d %H:%M:%S")
    session = Session()
    logs = session.query(ShopBidding).filter(ShopBidding.shopid == sid, ShopBidding.biddingTime >= today,
                                             ShopBidding.biddingTime <= todayPlus).all()
    shopInfo = getShopsInfo(sid, shopType)
    specialTime = shopInfo.get("specialTime", "")
    adTime = shopInfo.get("adTime", "")
    session.close()
    # 判断忙时的时间段
    try:
        specialTime = eval(specialTime)
        adTime = eval(adTime)
    except:
        specialTime = specialTime
        adTime = adTime
    # 所有的时间段
    item2 = []
    today = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S")
    todayTime = today.strftime("%Y-%m-%d")
    nowTime = todayTime + " " + datetime.datetime.now().strftime("%H:%M:%S")
    for i in range(24):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=60)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)
    busyTime = []
    for sTime in specialTime:
        if sTime.get("type") == 1:
            # 得到比startTime小的或者相等的时间整点，得到比endTime大的或者相等的时间整点
            startMinute = sTime['s'][-2:]
            endMinute = sTime['e'][-2:]
            if startMinute == '30':
                sTime['s'] = sTime['s'][:2] + ':00'
            if endMinute == '30':
                sTime['e'] = sTime['e'][:2] + ':00'
                midTime = todayTime + " " + sTime['e'] + ":00"
                sTime['e'] = (datetime.datetime.strptime(midTime, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(
                    hours=1)).strftime('%H:%M')
            startTime = todayTime + " " + sTime['s'] + ":00"  # 10:30
            endTime = todayTime + " " + sTime['e'] + ":00"
            for item in item2:
                if startTime < item[1] and item[1] <= endTime:
                    busyTime.append(item[0])
    realPeriodExposure = {}
    priceCount = {}
    priceDict = {}
    realTimeOrder = {}
    for item in item2:
        priceDict[item[1]] = {}
        realPeriodExposure[item[1]] = 0
        realTimeOrder[item[1]] = 0
        if date == datetime.datetime.now().strftime("%Y-%m-%d") + " 00:00:00":
            if item[0] < nowTime <= item[1]:
                break
    for i in range(len(logs) - 1):
        if i == 0:
            periodOrder = int(logs[i].realTimeOrder)
        else:
            periodOrder = int(logs[i + 1].realTimeOrder) - int(logs[i].realTimeOrder)
        periodExposure = int(logs[i + 1].exposureNum) - int(logs[i].exposureNum)
        for item in item2:
            if logs[i + 1].biddingTime > item[0] and logs[i + 1].biddingTime <= item[1]:
                if item[1] in priceDict.keys():
                    realPeriodExposure[item[1]] += periodExposure
                    realTimeOrder[item[1]] += periodOrder
                    if float(logs[i].basePrice) in priceDict[item[1]].keys():
                        priceDict[item[1]][float(logs[i].basePrice)] += periodExposure
                    else:
                        priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                else:
                    realTimeOrder[item[1]] = periodOrder
                    realPeriodExposure[item[1]] = periodExposure
                    priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                break
        if not float(logs[i].basePrice) in priceCount.keys():
            priceCount[float(logs[i].basePrice)] = periodExposure
        else:
            priceCount[float(logs[i].basePrice)] = priceCount[float(logs[i].basePrice)] + periodExposure
    # 全天的分布
    priceCount = sorted(priceCount.items(), key=lambda x: x[0])
    # 每半小时的分布
    orderCounts = []
    price = []
    count = []
    temp = {}
    for t in priceCount:
        price.append(t[0])
        count.append(t[1])
    orderCounts.append(price)
    orderCounts.append(count)
    maxPrice = []
    minPrice = []
    avgPrice = []
    hourPriceCounts = {}
    realTimeOrderList = []
    for kDict, vDict in priceDict.items():
        if vDict == {}:
            maxPrice.append(0)
            minPrice.append(0)
            avgPrice.append(0)
            hourPriceCounts[kDict] = None
        else:
            pDict = sorted(vDict.items(), key=lambda x: x[0])
            minPrice.append(pDict[0][0])
            maxPrice.append(pDict[-1][0])
            allNum = 0
            exposure = 0
            price = []
            priceNum = []
            for t in pDict:
                t = list(t)
                if t[1] == 0:
                    t[1] = 1
                allNum += t[0] * t[1]
                exposure += t[1]
                price.append(t[0])
                priceNum.append(t[1])
            if int(exposure) == 0:
                exposure = 1
                allNum = 0.1
            avgPrice.append(round(allNum / exposure, 2))
            hourPriceCounts[kDict] = {"price": price, "priceNum": priceNum}
    periodExposure = []
    for k, v in realPeriodExposure.items():
        periodExposure.append(v)
    for k, v in realTimeOrder.items():
        realTimeOrderList.append(v)

    # 处理小尾巴
    if periodExposure[-1] < 0:
        periodExposure[-1] = 0
    if realTimeOrderList[-1] < 0:
        realTimeOrderList[-1] = 0
    masterData = {"maxPrice": maxPrice, "minPrice": minPrice, "avgPrice": avgPrice}
    item = {"hourPriceCounts": hourPriceCounts, "allDayPriceCounts": orderCounts, "masterData": masterData,
            "periodExposure": periodExposure,
            "realTimeOrderList": realTimeOrderList, "busyTime": busyTime}
    return item


def getPriceCount(sid, shopType, date, app=0):
    '''
    获取前端主模块的数据
    :param sid: 真实的shopId
    :param shopType: 店铺种类
    :param date: 获取什么时间的数据
    :return:
    '''
    today = date
    todayPlus = (datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
        "%Y-%m-%d %H:%M:%S")
    session = Session()
    logs = session.query(ShopBidding).filter(ShopBidding.shopid == sid, ShopBidding.biddingTime >= today,
                                             ShopBidding.biddingTime <= todayPlus).all()
    shopInfo = getShopsInfo(sid, shopType)

    specialTime = shopInfo.get("specialTime", "")
    adTime = shopInfo.get("adTime", "")
    session.close()
    # 判断忙时的时间段
    try:
        specialTime = eval(specialTime)
        adTime = eval(adTime)
    except:
        specialTime = specialTime
        adTime = adTime
    # 所有的时间段
    item2 = []
    today = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S")
    todayTime = today.strftime("%Y-%m-%d")
    nowTime = todayTime + " " + datetime.datetime.now().strftime("%H:%M:%S")
    for i in range(48):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=30)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)
    busyTime = []
    for sTime in specialTime:
        if sTime.get("type") == 1:
            startTime = todayTime + " " + sTime['s'] + ":00"
            endTime = todayTime + " " + sTime['e'] + ":00"
            for item in item2:
                if startTime <= item[1] and item[1] < endTime:
                    busyTime.append(item[1])
    realPeriodExposure = {}
    priceCount = {}
    priceDict = {}
    realTimeOrder = {}
    for item in item2:
        priceDict[item[1]] = {}
        realPeriodExposure[item[1]] = 0
        realTimeOrder[item[1]] = 0
        if date == datetime.datetime.now().strftime("%Y-%m-%d") + " 00:00:00":
            if item[0] < nowTime <= item[1]:
                break
    for i in range(len(logs) - 1):
        if i == 0:
            periodOrder = int(logs[i].realTimeOrder)
        else:
            periodOrder = int(logs[i + 1].realTimeOrder) - int(logs[i].realTimeOrder)
        periodExposure = int(logs[i + 1].exposureNum) - int(logs[i].exposureNum)
        for item in item2:
            if logs[i + 1].biddingTime > item[0] and logs[i + 1].biddingTime <= item[1]:
                if item[1] in priceDict.keys():
                    realPeriodExposure[item[1]] += periodExposure
                    realTimeOrder[item[1]] += periodOrder
                    if float(logs[i].basePrice) in priceDict[item[1]].keys():
                        priceDict[item[1]][float(logs[i].basePrice)] += periodExposure
                    else:
                        priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                else:
                    realTimeOrder[item[1]] = periodOrder
                    realPeriodExposure[item[1]] = periodExposure
                    priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                break
        if not float(logs[i].basePrice) in priceCount.keys():
            priceCount[float(logs[i].basePrice)] = periodExposure
        else:
            priceCount[float(logs[i].basePrice)] = priceCount[float(logs[i].basePrice)] + periodExposure
    # 全天的分布
    priceCount = sorted(priceCount.items(), key=lambda x: x[0])
    # 每半小时的分布
    orderCounts = []
    price = []
    count = []
    temp = {}
    for t in priceCount:
        price.append(t[0])
        count.append(t[1])
    orderCounts.append(price)
    orderCounts.append(count)
    maxPrice = []
    minPrice = []
    avgPrice = []
    hourPriceCounts = {}
    realTimeOrderList = []
    for kDict, vDict in priceDict.items():
        if vDict == {}:
            maxPrice.append(0)
            minPrice.append(0)
            avgPrice.append(0)
            hourPriceCounts[kDict] = None
        else:
            pDict = sorted(vDict.items(), key=lambda x: x[0])
            minPrice.append(pDict[0][0])
            maxPrice.append(pDict[-1][0])
            allNum = 0
            exposure = 0
            price = []
            priceNum = []
            for t in pDict:
                t = list(t)
                if t[1] == 0:
                    t[1] = 1
                allNum += t[0] * t[1]
                exposure += t[1]
                price.append(t[0])
                priceNum.append(t[1])
            if int(exposure) == 0:
                exposure = 1
                allNum = 0.1
            avgPrice.append(round(allNum / exposure, 2))
            hourPriceCounts[kDict] = {"price": price, "priceNum": priceNum}
    periodExposure = []
    for k, v in realPeriodExposure.items():
        periodExposure.append(v)
    for k, v in realTimeOrder.items():
        realTimeOrderList.append(v)

    # 处理小尾巴
    if periodExposure[-1] < 0:
        periodExposure[-1] = 0
    if realTimeOrderList[-1] < 0:
        realTimeOrderList[-1] = 0
    masterData = {"maxPrice": maxPrice, "minPrice": minPrice, "avgPrice": avgPrice}
    item = {"hourPriceCounts": hourPriceCounts, "allDayPriceCounts": orderCounts, "masterData": masterData,
            "periodExposure": periodExposure,
            "realTimeOrderList": realTimeOrderList, "busyTime": busyTime}
    return item

def getPriceCountwithSessionwithShopInfo(session,eleShop,mtShop,sid, shopType, date, app=0):
    '''
    获取前端主模块的数据
    :param sid: 真实的shopId
    :param shopType: 店铺种类
    :param date: 获取什么时间的数据
    :return:
    '''
    today = date
    todayPlus = (datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
        "%Y-%m-%d %H:%M:%S")
    logs = session.query(ShopBidding).filter(ShopBidding.shopid == sid, ShopBidding.biddingTime >= today,
                                             ShopBidding.biddingTime <= todayPlus).all()
    shopInfo = getShopsInfowithShopInfo(eleShop ,mtShop , shopType)

    specialTime = shopInfo.get("specialTime", "")
    adTime = shopInfo.get("adTime", "")

    # 判断忙时的时间段
    try:
        specialTime = eval(specialTime)
        adTime = eval(adTime)
    except:
        specialTime = specialTime
        adTime = adTime
    # 所有的时间段
    item2 = []
    today = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S")
    todayTime = today.strftime("%Y-%m-%d")
    nowTime = todayTime + " " + datetime.datetime.now().strftime("%H:%M:%S")
    for i in range(48):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=30)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)
    busyTime = []
    for sTime in specialTime:
        if sTime.get("type") == 1:
            startTime = todayTime + " " + sTime['s'] + ":00"
            endTime = todayTime + " " + sTime['e'] + ":00"
            for item in item2:
                if startTime < item[1] and item[1] <= endTime:
                    busyTime.append(item[0])
    realPeriodExposure = {}
    priceCount = {}
    priceDict = {}
    realTimeOrder = {}
    for item in item2:
        priceDict[item[1]] = {}
        realPeriodExposure[item[1]] = 0
        realTimeOrder[item[1]] = 0
        if date == datetime.datetime.now().strftime("%Y-%m-%d") + " 00:00:00":
            if item[0] < nowTime <= item[1]:
                break
    for i in range(len(logs) - 1):
        if i == 0:
            periodOrder = int(logs[i].realTimeOrder)
        else:
            periodOrder = int(logs[i + 1].realTimeOrder) - int(logs[i].realTimeOrder)
        periodExposure = int(logs[i + 1].exposureNum) - int(logs[i].exposureNum)
        for item in item2:
            if logs[i + 1].biddingTime > item[0] and logs[i + 1].biddingTime <= item[1]:
                if item[1] in priceDict.keys():
                    realPeriodExposure[item[1]] += periodExposure
                    realTimeOrder[item[1]] += periodOrder
                    if float(logs[i].basePrice) in priceDict[item[1]].keys():
                        priceDict[item[1]][float(logs[i].basePrice)] += periodExposure
                    else:
                        priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                else:
                    realTimeOrder[item[1]] = periodOrder
                    realPeriodExposure[item[1]] = periodExposure
                    priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                break
        if not float(logs[i].basePrice) in priceCount.keys():
            priceCount[float(logs[i].basePrice)] = periodExposure
        else:
            priceCount[float(logs[i].basePrice)] = priceCount[float(logs[i].basePrice)] + periodExposure
    # 全天的分布
    priceCount = sorted(priceCount.items(), key=lambda x: x[0])
    # 每半小时的分布
    orderCounts = []
    price = []
    count = []
    temp = {}
    for t in priceCount:
        price.append(t[0])
        count.append(t[1])
    orderCounts.append(price)
    orderCounts.append(count)
    maxPrice = []
    minPrice = []
    avgPrice = []
    hourPriceCounts = {}
    realTimeOrderList = []
    for kDict, vDict in priceDict.items():
        if vDict == {}:
            maxPrice.append(0)
            minPrice.append(0)
            avgPrice.append(0)
            hourPriceCounts[kDict] = None
        else:
            pDict = sorted(vDict.items(), key=lambda x: x[0])
            minPrice.append(pDict[0][0])
            maxPrice.append(pDict[-1][0])
            allNum = 0
            exposure = 0
            price = []
            priceNum = []
            for t in pDict:
                t = list(t)
                if t[1] == 0:
                    t[1] = 1
                allNum += t[0] * t[1]
                exposure += t[1]
                price.append(t[0])
                priceNum.append(t[1])
            if int(exposure) == 0:
                exposure = 1
                allNum = 0.1
            avgPrice.append(round(allNum / exposure, 2))
            hourPriceCounts[kDict] = {"price": price, "priceNum": priceNum}
    periodExposure = []
    for k, v in realPeriodExposure.items():
        periodExposure.append(v)
    for k, v in realTimeOrder.items():
        realTimeOrderList.append(v)

    # 处理小尾巴
    if periodExposure[-1] < 0:
        periodExposure[-1] = 0
    if realTimeOrderList[-1] < 0:
        realTimeOrderList[-1] = 0
    masterData = {"maxPrice": maxPrice, "minPrice": minPrice, "avgPrice": avgPrice}
    item = {"hourPriceCounts": hourPriceCounts, "allDayPriceCounts": orderCounts, "masterData": masterData,
            "periodExposure": periodExposure,
            "realTimeOrderList": realTimeOrderList, "busyTime": busyTime}
    return item


def getHeadInfos(shopId, shopType):
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId, ShopEleInfo.shopType == shopType).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId,
                                               ShopMeituanInfo.shopType == shopType).first()
    session.close()
    cookies = ''
    targetExposure = 0
    todayBudget = 0

    today = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    # lastLog =  session.query(ShopBidding).filter(ShopBidding.shopid == shopId,ShopBidding.biddingTime>=today).first()
    # session.close()
    # todayBudget = float(lastLog.todayBudget)

    if ele:
        cookies = ele.cookies
        targetExposure = ele.targetExposure
        todayBudget = ele.budget
    elif mt:
        cookies = mt.cookies
        targetExposure = mt.targetExposure
        todayBudget = mt.budget
    if shopType == 1:
        mt = MTSpider(cookies)
        exposure = mt.gettodayExposure()
        clickCount = exposure.get("data", {}).get("clickCount")
        showCount = exposure.get("data", {}).get("showCount")
        currentCost = exposure.get("data", {}).get("cost")
        avgPrice = exposure.get("data", {}).get("avgPrice")

        avgSevenShopInfo = mt.getAvgSevenShopInfo()
        daysAvgClickCount = int(avgSevenShopInfo.get("clickCount", 0) / 7)
        daysAvgCost = round(avgSevenShopInfo.get("cost") / 7, 2)
        daysAvgPrice = avgSevenShopInfo.get("avgPrice", 0)
        return {"item1": {"showCount": showCount, "targetExposure": targetExposure},
                "item2": {"clickCount": clickCount, "daysAvgClickCount": daysAvgClickCount},
                "item3": {"currentCost": currentCost, "todayBudget": todayBudget, "daysAvgCost": daysAvgCost},
                "item4": {"avgPrice": avgPrice, "daysAvgPrice": daysAvgPrice}}

    elif shopType == 2:
        ele = ELESpider(cookies)
        exposure = ele.gettodayExposure()
        clickCount = exposure.get('result', {}).get('uvCount', 0)
        showCount = exposure.get("result", {}).get("totalExposureAmount", 0)
        currentCost = exposure.get("result", {}).get("totalCost", 0)
        avgPrice = exposure.get("result", {}).get("averageCost", 0)

        daysExposure = ele.get7DaysExposure()
        daysAvgClickCount = int(daysExposure.get("uvCount", 0) / 7)
        daysAvgCost = int(daysExposure.get("totalCost", 0) / 7)
        daysAvgPrice = daysExposure.get("averageCost", 0)
        return {"item1": {"showCount": showCount, "targetExposure": targetExposure},
                "item2": {"clickCount": clickCount, "daysAvgClickCount": daysAvgClickCount},
                "item3": {"currentCost": currentCost, "todayBudget": todayBudget, "daysAvgCost": daysAvgCost},
                "item4": {"avgPrice": avgPrice, "daysAvgPrice": daysAvgPrice}}

def getHeadInfoswithShopInfo(ele,mt, shopType):
    cookies = ''
    targetExposure = 0
    todayBudget = 0

    # lastLog =  session.query(ShopBidding).filter(ShopBidding.shopid == shopId,ShopBidding.biddingTime>=today).first()
    # session.close()
    # todayBudget = float(lastLog.todayBudget)

    if ele:
        cookies = ele.cookies
        targetExposure = ele.targetExposure
        todayBudget = ele.budget
    elif mt:
        cookies = mt.cookies
        targetExposure = mt.targetExposure
        todayBudget = mt.budget
    if shopType == 1:
        mt = MTSpider(cookies)
        exposure = mt.gettodayExposure()
        clickCount = exposure.get("data", {}).get("clickCount")
        showCount = exposure.get("data", {}).get("showCount")
        currentCost = exposure.get("data", {}).get("cost")
        avgPrice = exposure.get("data", {}).get("avgPrice")

        avgSevenShopInfo = mt.getAvgSevenShopInfo()
        daysAvgClickCount = int(avgSevenShopInfo.get("clickCount", 0) / 7)
        daysAvgCost = round(avgSevenShopInfo.get("cost") / 7, 2)
        daysAvgPrice = avgSevenShopInfo.get("avgPrice", 0)
        return {"item1": {"showCount": showCount, "targetExposure": targetExposure},
                "item2": {"clickCount": clickCount, "daysAvgClickCount": daysAvgClickCount},
                "item3": {"currentCost": currentCost, "todayBudget": todayBudget, "daysAvgCost": daysAvgCost},
                "item4": {"avgPrice": avgPrice, "daysAvgPrice": daysAvgPrice}}

    elif shopType == 2:
        ele = ELESpider(cookies)
        exposure = ele.gettodayExposure()
        clickCount = exposure.get('result', {}).get('uvCount', 0)
        showCount = exposure.get("result", {}).get("totalExposureAmount", 0)
        currentCost = exposure.get("result", {}).get("totalCost", 0)
        avgPrice = exposure.get("result", {}).get("averageCost", 0)

        daysExposure = ele.get7DaysExposure()
        daysAvgClickCount = int(daysExposure.get("uvCount", 0) / 7)
        daysAvgCost = int(daysExposure.get("totalCost", 0) / 7)
        daysAvgPrice = daysExposure.get("averageCost", 0)
        return {"item1": {"showCount": showCount, "targetExposure": targetExposure},
                "item2": {"clickCount": clickCount, "daysAvgClickCount": daysAvgClickCount},
                "item3": {"currentCost": currentCost, "todayBudget": todayBudget, "daysAvgCost": daysAvgCost},
                "item4": {"avgPrice": avgPrice, "daysAvgPrice": daysAvgPrice}}


def getShopBaseInfo(shopid, type):
    session = Session()
    shopInfo = {}
    eleShop = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopid).first()
    mtShop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopid).first()
    if eleShop:
        shopInfo['isEnable'] = eleShop.isenable
        shopInfo['targetExposure'] = eleShop.targetExposure
        shopInfo['budget'] = eleShop.budget
        shopInfo['adTime'] = eleShop.adTime
        shopInfo['account'] = eleShop.account
        cookies = eleShop.cookies
        curbid = 0
        try:
            ele = ELESpider(cookies)
            adPrice = ele.getAdPrice()
            curbid = adPrice.get("grade", 0)
        except:
            curbid = 0
        shopInfo['curbid'] = curbid
    elif mtShop:
        shopInfo['isEnable'] = mtShop.isenable
        shopInfo['targetExposure'] = mtShop.targetExposure
        shopInfo['budget'] = mtShop.budget
        shopInfo['adTime'] = mtShop.adTime
        shopInfo['account'] = mtShop.account
        cookies = mtShop.cookies
        curbid = 0
        try:
            mt = MTSpider(cookies)
            details = mt.getDetail(None)
            curbid = float(details.get("bid") / 100)
        except:
            curbid = 0
        shopInfo['curbid'] = curbid
    return shopInfo

def getShopBaseInfowithShopInfo(eleShop, mtShop , type):
    shopInfo = {}
    if eleShop:
        shopInfo['isEnable'] = eleShop.isenable
        shopInfo['targetExposure'] = eleShop.targetExposure
        shopInfo['budget'] = eleShop.budget
        shopInfo['adTime'] = eleShop.adTime
        shopInfo['account'] = eleShop.account
        cookies = eleShop.cookies
        curbid = 0
        try:
            ele = ELESpider(cookies)
            adPrice = ele.getAdPrice()
            curbid = adPrice.get("grade", 0)
        except:
            curbid = 0
        shopInfo['curbid'] = curbid
    elif mtShop:
        shopInfo['isEnable'] = mtShop.isenable
        shopInfo['targetExposure'] = mtShop.targetExposure
        shopInfo['budget'] = mtShop.budget
        shopInfo['adTime'] = mtShop.adTime
        shopInfo['account'] = mtShop.account
        cookies = mtShop.cookies
        curbid = 0
        try:
            mt = MTSpider(cookies)
            details = mt.getDetail(None)
            curbid = float(details.get("bid") / 100)
        except:
            curbid = 0
        shopInfo['curbid'] = curbid
    return shopInfo


def newGetPeriodTarget(shopId, type, date):
    session = Session()
    ele = session.query(ShopInfo).filter(ShopInfo.eleId == shopId).first()
    mt = session.query(ShopInfo).filter(ShopInfo.mtId == shopId).first()
    session.close()
    account = None
    if ele:
        account = ele.eleaccount
    elif mt:
        account = mt.mtaccount
    if date:
        today = date
    else:
        todayDateTime = datetime.datetime.now()
        today = todayDateTime.strftime("%Y-%m-%d 00:00:00")
    todayPlus = (datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
        "%Y-%m-%d %H:%M:%S")
    session = Session()
    plans = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.account == account,
                                                    ShopBiddingTarget.exposureTime >= today,
                                                    ShopBiddingTarget.exposureTime < todayPlus).all()
    session.close()
    if len(plans) == 0:
        return
    item2 = []
    today = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S")
    for i in range(144):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=10)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)
    periodTargetDict = {}
    for item in item2:
        periodTargetDict[item[1]] = 0
    for i in range(len(plans) - 1):
        periodExposure = int(plans[i + 1].exposureNum) - int(plans[i].exposureNum)
        for item in item2:
            if plans[i + 1].exposureTime > item[0] and plans[i + 1].exposureTime < item[1]:
                if item[1] in periodTargetDict.keys():
                    periodTargetDict[item[1]] += periodExposure
                else:
                    periodTargetDict[item[1]] = periodExposure
                break
    periodTargetList = []
    for k, v in periodTargetDict.items():
        periodTargetList.append(v)
    return periodTargetList


def getPeriodTargetHour(shopId, type, date):
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    session.close()
    account = None
    if ele:
        account = ele.account
    elif mt:
        account = mt.account
    if date:
        today = date
    else:
        todayDateTime = datetime.datetime.now()
        today = todayDateTime.strftime("%Y-%m-%d 00:00:00")
    todayPlus = (datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
        "%Y-%m-%d %H:%M:%S")
    session = Session()
    plans = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.account == account,
                                                    ShopBiddingTarget.exposureTime >= today,
                                                    ShopBiddingTarget.exposureTime < todayPlus).all()
    session.close()
    if len(plans) == 0:
        return
    item2 = []
    today = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S")
    for i in range(48):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=30)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)
    periodTargetDict = {}
    for item in item2:
        periodTargetDict[item[1]] = 0
    for i in range(len(plans) - 1):
        periodExposure = int(plans[i + 1].exposureNum) - int(plans[i].exposureNum)
        for item in item2:
            if plans[i + 1].exposureTime > item[0] and plans[i + 1].exposureTime <= item[1]:
                if item[1] in periodTargetDict.keys():
                    periodTargetDict[item[1]] += periodExposure
                else:
                    periodTargetDict[item[1]] = periodExposure
                break
    periodTargetList = []
    index = 1
    for k, v in periodTargetDict.items():
        periodTargetList.append(v)
    periodTargetListBack = []
    for i in range(0, 24):
        periodTargetListBack.append(periodTargetList[2 * i] + periodTargetList[2 * i + 1])
    return periodTargetListBack


def getPeriodTarget(shopId, type, date):
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    session.close()
    account = None
    if ele:
        account = ele.account
    elif mt:
        account = mt.account
    if date:
        today = date
    else:
        todayDateTime = datetime.datetime.now()
        today = todayDateTime.strftime("%Y-%m-%d 00:00:00")
    todayPlus = (datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
        "%Y-%m-%d %H:%M:%S")
    session = Session()
    plans = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.account == account,
                                                    ShopBiddingTarget.exposureTime >= today,
                                                    ShopBiddingTarget.exposureTime < todayPlus).all()
    session.close()
    if len(plans) == 0:
        return
    item2 = []
    today = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S")
    for i in range(48):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=30)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)
    periodTargetDict = {}
    for item in item2:
        periodTargetDict[item[1]] = 0
    for i in range(len(plans) - 1):
        periodExposure = int(plans[i + 1].exposureNum) - int(plans[i].exposureNum)
        for item in item2:
            if plans[i + 1].exposureTime > item[0] and plans[i + 1].exposureTime < item[1]:
                if item[1] in periodTargetDict.keys():
                    periodTargetDict[item[1]] += periodExposure
                else:
                    periodTargetDict[item[1]] = periodExposure
                break
    periodTargetList = []
    for k, v in periodTargetDict.items():
        periodTargetList.append(v)
    return periodTargetList

def getPeriodTargetwithSession(session,shopId, type, date):
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    account = None
    if ele:
        account = ele.account
    elif mt:
        account = mt.account
    if date:
        today = date
    else:
        todayDateTime = datetime.datetime.now()
        today = todayDateTime.strftime("%Y-%m-%d 00:00:00")
    todayPlus = (datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime(
        "%Y-%m-%d %H:%M:%S")
    session = Session()
    plans = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.account == account,
                                                    ShopBiddingTarget.exposureTime >= today,
                                                    ShopBiddingTarget.exposureTime < todayPlus).all()
    session.close()
    if len(plans) == 0:
        return
    item2 = []
    today = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S")
    for i in range(48):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=30)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)
    periodTargetDict = {}
    for item in item2:
        periodTargetDict[item[1]] = 0
    for i in range(len(plans) - 1):
        periodExposure = int(plans[i + 1].exposureNum) - int(plans[i].exposureNum)
        for item in item2:
            if plans[i + 1].exposureTime > item[0] and plans[i + 1].exposureTime <= item[1]:
                if item[1] in periodTargetDict.keys():
                    periodTargetDict[item[1]] += periodExposure
                else:
                    periodTargetDict[item[1]] = periodExposure
                break
    periodTargetList = []
    for k, v in periodTargetDict.items():
        periodTargetList.append(v)
    return periodTargetList


def checkManager(manager):
    try:
        session = Session()
        manager = session.query(Admin.userName).filter(Admin.userName == manager).scalar()
        session.close()
        if not manager:
            return 1000
        return True
    except:
        return False


def addANewShop(shopData1, shopData2, shopType):
    session = Session()
    createtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if int(shopType) == 1:
        mtName = shopData1.get("name")
        account = shopData1.get("account")
        shopType = shopData1.get("shopType")
        isenable = shopData1.get("isenable")
        isbind = shopData1.get("isbind")
        userName = shopData1.get("username")
        targetExposure = shopData1.get("targetExposure")
        budget = shopData1.get("budget")
        shopName = session.query(ShopMeituanInfo.mtName).filter(ShopMeituanInfo.account == account).scalar()
        if shopName:
            return 1000
        session.add(
            ShopMeituanInfo(
                mtName=mtName,
                account=account,
                shopType=shopType,
                isenable=isenable,
                isbind=isbind,
                userName=userName,
                targetExposure=targetExposure,
                budget=budget,
                createtime=createtime,
                updatetime=createtime,
            )
        )

        session.commit()
        session.close()

    elif int(shopType) == 2:
        eleName = shopData1.get("name")
        account = shopData1.get("account")
        shopType = shopData1.get("shopType")
        isenable = shopData1.get("isenable")
        isbind = shopData1.get("isbind")
        userName = shopData1.get("username")
        targetExposure = shopData1.get("targetExposure")
        budget = shopData1.get("budget")
        shopName = session.query(ShopEleInfo.eleName).filter(ShopEleInfo.account == account).scalar()
        if shopName:
            return 1000
        session.add(
            ShopEleInfo(
                eleName=eleName,
                account=account,
                shopType=shopType,
                isenable=isenable,
                isbind=isbind,
                userName=userName,
                targetExposure=targetExposure,
                budget=budget,
                createtime=createtime,
                updatetime=createtime,
            )
        )

        session.commit()
        session.close()


def getPeriodShopInfo(sid):
    today = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    session = Session()
    logs = session.query(ShopBidding).filter(ShopBidding.shopid == sid, ShopBidding.biddingTime >= today).all()
    session.close()
    periodData = {}

    # allExposure = logs[len(logs) - 1].allExposure
    # realExposure = logs[len(logs) - 1].exposureNum
    periodTarget = []
    periodTarget.append(0)

    plans = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.shopid == sid,
                                                    ShopBiddingTarget.exposureTime >= today).all()
    for i in range(15, len(plans), 15):
        periodTarget.append(round(float(plans[i].targetNum) - float(plans[i - 15].targetNum), 2))

    periodCost = []
    periodVisitNum = []
    periodRate = []
    periodAllExposure = []
    periodRealExposure = []

    businessAmount = []
    realTimeOrder = []
    percentBudget = []
    if len(logs) == 0:
        return

    periodCost.append(0)
    periodVisitNum.append(0)
    periodAllExposure.append(0)
    periodRealExposure.append(0)

    businessAmount.append(float(logs[0].businessAmount))
    realTimeOrder.append(0)
    percentBudget.append(float(logs[0].percentBudget))

    for i in range(15, len(logs), 15):
        # periodTarget.append(round(float(logs[i].targetNum) - float(logs[i - 5].targetNum), 2))

        # periodCost.append(round(float(logs[i - 5].blance) - float(logs[i].blance) , 2))
        # periodVisitNum.append(round(float(logs[i].visitNum) - float(logs[i - 5].visitNum), 2))
        # periodAllExposure.append(round(float(logs[i].allExposure) - float(logs[i - 5].allExposure), 2))
        periodRealExposure.append(round(float(logs[i].exposureNum) - float(logs[i - 15].exposureNum), 2))
        # businessAmount.append(round(float(logs[i].businessAmount),2))
        # realTimeOrder.append(round(float(logs[i].realTimeOrder) - float(logs[i - 5].realTimeOrder), 2))
        # percentBudget.append(float(logs[i].percentBudget))
    # for i in range(len(periodCost)):
    #     if int(periodVisitNum[i]) != 0:
    #         periodRate.append(round(float(periodCost[i]) / float(periodVisitNum[i]),4))
    #     else:
    #         periodRate.append(round(float(periodCost[i]),4))

    table1 = {}
    item1 = {}

    item1['periodCost'] = periodCost
    item1['periodRate'] = periodRate

    table1['item1'] = item1

    table2 = {}

    table2['periodAllExposure'] = periodAllExposure
    table2['periodRealExposure'] = periodRealExposure
    table2['periodTarget'] = periodTarget

    table3 = {}

    table3['businessAmount'] = businessAmount

    # table4 = {}
    # table4['allExposure'] = allExposure
    # table4['realExposure'] = realExposure
    #
    # table5 = {}
    # table5['percentBudget'] = percentBudget[len(percentBudget) - 1]

    tables = []
    tables.append(table1)
    tables.append(table2)
    tables.append(table3)
    # tables.append(table4)
    # tables.append(table5)
    return tables


'''
七日订单，10分钟为一个周期

'''


def newGetPeriod7DaysOrder(shopId, type):
    today = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).first()
    # percent = None
    account = None
    if ele:
        account = ele.account
        # percent = ele.percent
    elif mt:
        account = mt.account
        # percent = mt.percent
    session = Session()
    orders = session.query(YesOrderInfo.orderDetail).filter(YesOrderInfo.account == account).order_by(
        YesOrderInfo.id.desc())[0:7]
    session.close()
    yesOrders = orders[0]
    # try:
    #     percent = eval(percent)
    # except:
    #     percent = percent
    # for n in range(len(percent)):
    #     percent[n] = round(percent[n] / len(orders),2)

    if not yesOrders[0]:
        yesOrders = []
    if yesOrders:
        try:
            yesOrders = eval(yesOrders[0])
        except:
            yesOrders = yesOrders
    orderNumOfSeven = 0  # 七日的全天订单
    count = 0
    yesNum = 0  # 昨日的订单
    hourOrderNum = [0 for i in range(0, 144)]
    hourOrderNumOfSeven = []
    for order in orders:
        if order[0]:
            orderlst = eval(order[0])
            count += 1
            for i in range(0, len(orderlst)):
                orderNumOfSeven += orderlst[i]
                hourOrderNum[i] += orderlst[i]
    for i in range(len(yesOrders)):
        hourOrderNumOfSeven.append(round(float(hourOrderNum[i] / count), 2))
        yesNum += yesOrders[i]
    orderNumOfSeven = int(orderNumOfSeven / count)
    ##判断当前时间对应的48个数的序号
    return {"orderNumOfSeven": orderNumOfSeven, "yesNum": yesNum, "hourOrderNumOfSeven": hourOrderNumOfSeven}


def getPeriod7DaysOrder(shopId, type):
    today = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).first()

    yes = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")

    account = None
    if ele:
        account = ele.account
    elif mt:
        account = mt.account

    yesOrders = session.query(YesOrderInfo.InfoList).filter(YesOrderInfo.day == yes,
                                                            YesOrderInfo.account == account).scalar()
    orders = session.query(YesOrderInfo.InfoList).filter(YesOrderInfo.account == account).order_by(
        YesOrderInfo.id.desc())[0:7]
    session.close()

    yesNum = 0  # 昨日的订单
    if yesOrders:
        yesOrders = eval(yesOrders)
        yesNum = sum(yesOrders)

    orderNumOfSeven = 0  # 七日的全天订单
    count = 0
    hourOrderNum = [0 for i in range(0, 48)]
    hourOrderNumOfSeven = []
    for order in orders:
        if order[0]:
            orderlst = eval(order[0])
            count += 1
            for i in range(0, len(orderlst)):
                orderNumOfSeven += orderlst[i]
                hourOrderNum[i] += orderlst[i]
    for i in range(48):
        hourOrderNumOfSeven.append(round(float(hourOrderNum[i] / count), 2))

    orderNumOfSeven = int(orderNumOfSeven / count)
    ##判断当前时间对应的48个数的序号
    return {"orderNumOfSeven": orderNumOfSeven, "yesNum": yesNum, "hourOrderNumOfSeven": hourOrderNumOfSeven}

def getPeriod7DaysOrderwithSession(session,shopId, type):
    today = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).first()

    yes = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")

    account = None
    if ele:
        account = ele.account
    elif mt:
        account = mt.account

    yesOrders = session.query(YesOrderInfo.InfoList).filter(YesOrderInfo.day == yes,
                                                            YesOrderInfo.account == account).scalar()
    orders = session.query(YesOrderInfo.InfoList).filter(YesOrderInfo.account == account).order_by(
        YesOrderInfo.id.desc())[0:7]
    session.close()

    yesNum = 0  # 昨日的订单
    if yesOrders:
        yesOrders = eval(yesOrders)
        yesNum = sum(yesOrders)

    orderNumOfSeven = 0  # 七日的全天订单
    count = 0
    hourOrderNum = [0 for i in range(0, 48)]
    hourOrderNumOfSeven = []
    for order in orders:
        if order[0]:
            orderlst = eval(order[0])
            count += 1
            for i in range(0, len(orderlst)):
                orderNumOfSeven += orderlst[i]
                hourOrderNum[i] += orderlst[i]
    for i in range(48):
        hourOrderNumOfSeven.append(round(float(hourOrderNum[i] / count), 2))

    orderNumOfSeven = int(orderNumOfSeven / count)
    ##判断当前时间对应的48个数的序号
    return {"orderNumOfSeven": orderNumOfSeven, "yesNum": yesNum, "hourOrderNumOfSeven": hourOrderNumOfSeven}


def getPeriod7DaysOrderHour(shopId, type):
    today = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).first()

    yes = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")

    account = None
    if ele:
        account = ele.account
    elif mt:
        account = mt.account

    yesOrders = session.query(YesOrderInfo.InfoList).filter(YesOrderInfo.day == yes,
                                                            YesOrderInfo.account == account).scalar()
    orders = session.query(YesOrderInfo.InfoList).filter(YesOrderInfo.account == account).order_by(
        YesOrderInfo.id.desc())[0:7]
    session.close()

    yesNum = 0  # 昨日的订单
    if yesOrders:
        yesOrders = eval(yesOrders)
        yesNum = sum(yesOrders)

    orderNumOfSeven = 0  # 七日的全天订单
    count = 0
    hourOrderNum = [0 for i in range(0, 48)]
    hourOrderNumOfSeven = []
    for order in orders:
        if order[0]:
            orderlst = eval(order[0])
            count += 1
            for i in range(0, len(orderlst)):
                orderNumOfSeven += orderlst[i]
                hourOrderNum[i] += orderlst[i]
    for i in range(48):
        hourOrderNumOfSeven.append(round(float(hourOrderNum[i] / count), 2))

    hourOrderNumOfSevenBack = []
    for i in range(24):
        hourOrderNumOfSevenBack.append(hourOrderNumOfSeven[2 * i] + hourOrderNumOfSeven[2 * i + 1])
    orderNumOfSeven = int(orderNumOfSeven / count)
    ##判断当前时间对应的48个数的序号
    return {"orderNumOfSeven": orderNumOfSeven, "yesNum": yesNum, "hourOrderNumOfSeven": hourOrderNumOfSevenBack}


def getShopLogs(sid, start, end):
    today = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    s = Session()
    sql = s.query(ShopBidding).filter(ShopBidding.shopid == sid, ShopBidding.biddingTime >= start,
                                      ShopBidding.biddingTime <= end).order_by(ShopBidding.biddingTime.desc())
    result = sql.all()

    budget = 0
    ele = s.query(ShopEleInfo).filter(ShopEleInfo.eleId == sid).first()
    mt = s.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == sid).first()
    if ele:
        budget = ele.budget
    elif mt:
        budget = mt.budget

    s.close()
    Lst = []
    for b in result:
        btargetNum = b.targetNum
        bexposureNum = b.exposureNum
        brealTimeOrder = b.realTimeOrder
        if btargetNum:
            btargetNum = int(btargetNum)
        if bexposureNum:
            bexposureNum = int(bexposureNum)
        if brealTimeOrder:
            brealTimeOrder = int(brealTimeOrder)
        biddInfo = (dict(
            shopid=b.shopid,
            biddingtime = b.biddingTime[11:16],
            targetnum=b.targetNum,
            exposurenum=b.exposureNum,
            baseprice=b.basePrice,
            directprice=b.directPrice,
            log=b.log,
            status=b.status,
            blance=b.blance,
            shoptype="美团" if b.shoptype == 1 else "饿了么",
            isbybudget=b.isbybudget,
            visitNum=b.visitNum,
            exLog=b.exLog,
            budget=b.directPrice,
            periodtarget=b.periodtarget,
            periodexposure=b.periodexposure,
            businessAmount=b.businessAmount,
            realTimeOrder=str(brealTimeOrder) + "/" + str(b.visitNum),
            currentCost=str(b.currentCost) + "/" + str(budget),
        ))
        Lst.append(biddInfo)
    return Lst


def getAccountById(id):
    session = Session()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == id).first()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == id).first()
    session.close()
    if mt:
        return (mt.account, 1)
    elif ele:
        return (ele.account, 2)
    else:
        return None


def getIdByName(findby, shoptype):
    # session = Session()
    # mt = None
    # ele = None
    # print(shoptype)
    # print(type(shoptype))
    # if shoptype == '1':
    #     mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtName.ilike('%'+findby+'%')).all()
    # elif shoptype == '2':
    #     ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleName.ilike('%'+findby+'%')).all()
    # session.close()
    # if mt:
    #     return mt.mtId
    # elif ele:
    #     return ele.eleId
    # else:
    #     return None
    session = Session()
    mt = None
    ele = None
    print(shoptype)
    print(type(shoptype))
    if shoptype == '1':
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtName.ilike(findby)).scalar()
    elif shoptype == '2':
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleName.ilike(findby)).scalar()
    session.close()
    if mt:
        return mt.mtId
    elif ele:
        return ele.eleId
    else:
        return None


def getUserInfo(token):
    '''
    获取用户信息
    :param token:
    :return:
    '''
    userinfo = {}
    try:

        session = Session()
        user = session.query(User).filter(User.password == token).first()
        session.close()
        if not user:
            userinfo.update(code=config.FAIL_USER)
            return userinfo
        userinfo.update({"id": user.id,
                         "username": user.username,
                         "password": user.password,
                         "realname": user.realname,
                         "phone": user.phone,
                         "ispay": user.ispay,
                         "expiretime": user.expiretime,
                         "code": config.SUCCESS
                         })
        return userinfo
    except:
        logger.warning(traceback.format_exc())
        userinfo.update(code=config.PENNDING_ERROR)
        return userinfo


def userRegister(username, pwd, **kwargs):
    '''
    用户注册
    :param username:
    :param pwd:
    :param kwargs:
    :return:
    '''
    try:
        phone = kwargs.get("phone")
        realname = kwargs.get("realname")
        salt = kwargs.get("salt", 0)
        masterid = kwargs.get("masterid")
        openId = kwargs.get("openId")
        userid = 0
        session = Session()
        if openId:
            user = session.query(User).filter(or_(User.username == username, User.openId == openId)).scalar()
        else:
            user = session.query(User).filter(or_(User.username == username)).scalar()
        result = config.SUCCESS
        if not user:
            userinfo = User(
                username=username,
                password=pwd,
                phone=phone,
                salt=salt,
                realname=realname,
                expiretime=int(time.time()) + config.NEW_USER_EXPIRETIME,
                openId=openId
            )
            session.add(userinfo)
            session.commit()
            session.flush()
            userid = userinfo.id
            try:
                if masterid:
                    master = session.query(User).filter(User.id == masterid).scalar()
                    if master:
                        master.expiretime = master.expiretime + config.MASTER_USER_EXPIRETIME
                        session.add(
                            UserInvitationPayDetail(
                                userId=masterid,
                                slaveid=userid,
                                addtype=1,
                                adddays=config.NEW_USER_EXPIRETIME,
                                createtime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            )
                        )
                        session.commit()
            except:
                logger.warning(traceback.format_exc())
        else:
            logger.info("{}:已经存在".format(username))
            result = config.FAIL_USER
        session.close()
        return result
    except:
        logger.error(traceback.format_exc())
        return config.PENNDING_ERROR


def getAllMeituanShops():
    session = Session()
    shops = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.deleted == 0, ShopMeituanInfo.cookies != '').all()
    session.close()
    return shops


def getAllMeituanShopsforBidding():
    session = Session()
    shops = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.deleted == 0, ShopMeituanInfo.cookies != '',
                                                  ShopMeituanInfo.isenable == 1).all()
    session.close()
    return shops


def getAllEleShops():
    session = Session()
    shops = session.query(ShopEleInfo).filter(ShopEleInfo.deleted == 0, ShopEleInfo.cookies != '').all()
    session.close()
    return shops


def getAllEleShopsforBidding():
    session = Session()
    shops = session.query(ShopEleInfo).filter(ShopEleInfo.deleted == 0, ShopEleInfo.cookies != '',
                                              ShopEleInfo.isenable == 1).all()
    session.close()
    return shops


def updShopMeituanInfo(**kwargs):
    '''
    更新美团信息
    :param args:
    :param kwargs:
    :return:
    '''
    try:
        account = kwargs.get("account")
        mtid = kwargs.get("mtId")
        ct = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        mtbudget = kwargs.get('mtbudget')
        mtisenable = kwargs.get("mtisenable", None)
        mttargetExposure = kwargs.get("mttargetExposure")
        deleted = kwargs.get("deleted", None)
        shipTime = kwargs.get("mtshiptime", '')  # 营业时间段
        adtime = kwargs.get("mtadtime")
        percent = kwargs.get("percent")
        specialtime = kwargs.get("specialtime")
        keepSameStatus = kwargs.get("keepSameStatus")
        serviceTime = kwargs.get("serviceTime")
        idleExposureRate = kwargs.get("idleExposureRate")
        idleOrderRateList = kwargs.get("idleOrderRateList")
        busyOrderRate = kwargs.get("busyOrderRate")
        daysAvgPrice = kwargs.get("daysAvgPrice")

        busyTimeLock = kwargs.get("busyTimeLock")
        controlRate = kwargs.get("controlRate")
        baseRate = kwargs.get("baseRate")

        nextExposureRate = kwargs.get("nextExposureRate")

        allExposureRate = kwargs.get("allExposureRate")

        session = Session()
        mt = None
        if account:
            mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()

        elif mtid:
            mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == mtid).scalar()

        if mttargetExposure is not None:
            mt.targetExposure = mttargetExposure
        if idleExposureRate is not None:
            mt.shopTimeEnd = str(idleExposureRate)
        if allExposureRate != None:
            mt.shopTimeStart = str(allExposureRate)

        # plan = mt.plan
        # if plan:
        #     try:
        #         plan = eval(plan)
        #         plan["nextExposureRate"] = nextExposureRate
        #         plan = str(plan)
        #         mt.plan = plan
        #     except:
        #         logger.info(traceback.format_exc())
        # else:
        #     plan = {}
        #     plan["nextExposureRate"] = nextExposureRate
        #     plan = str(plan)
        #     mt.plan = plan
        if idleOrderRateList != None and busyOrderRate != None and daysAvgPrice != None:
            mt.orderRate = str({"idleOrderRateList" : idleOrderRateList, "busyOrderRate" : busyOrderRate, "daysAvgPrice":daysAvgPrice})
        if controlRate != None and baseRate != None and nextExposureRate != None:
            mt.exposureRate = str({"controlRate":float(controlRate),"baseRate" : float(baseRate), "nextExposureRate" : nextExposureRate})
        if busyTimeLock != None:
            mt.busyTimeLock = int(busyTimeLock)

        if mtbudget is not None:
            mt.budget = mtbudget
        if deleted is not None:
            mt.deleted = deleted
        if mtisenable is not None:
            mt.isenable = mtisenable
        if shipTime:
            mt.shipTime = shipTime
        if adtime:
            mt.adTime = adtime

        if percent:
            mt.percent = percent
        if specialtime and not mt.specialtime:
            mt.specialtime = specialtime
        if serviceTime:
            mt.serviceTime = serviceTime
        if keepSameStatus is not None:
            mt.keepSameStatus = keepSameStatus
        mt.updatetime = ct
        session.commit()
        session.close()
    except:
        logger.warning(traceback.format_exc())

def getMTinfo(account):
    '''
    通过id获取美团信息
    :param mtid:
    :return:
    '''
    mtinfo={}
    try:
        session=Session()
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()

        session.close()
        adtime=[]
        percent=[]

        if mt:
            try:
                adtime=eval(mt.adTime)
                percent = eval(mt.percent)
            except:
                adtime=adtime
                percent = percent

            mtinfo=dict(
            id=mt.mtId,
            account=mt.account,
            name=mt.mtName,
            shoptimestart=mt.shopTimeStart,
            shoptimeend=mt.shopTimeEnd,
            shopstatus=mt.shopStatus,
            cookies=mt.cookies,
            budget=mt.budget,
            isenable=mt.isenable,
            isbind=mt.isbind,
            isonline=mt.isonline,
            targetexposure=mt.targetExposure,
            createtime=mt.createtime,
            adtime=adtime,
            isbybudget=mt.isbybudget if mt.isbybudget else 0,
            isremake=mt.isremake,
            percent=percent,
            updatetime=mt.updatetime,
            shipTime = mt.shipTime,
            specialtime = mt.specialtime,
            shopId=mt.shopId,
            salt=mt.salt,
            userName=mt.userName,
            historyCurbid = mt.historyCurbid,
            idleExposureRate= mt.shopTimeEnd,
            allExposureRate=mt.shopTimeStart,
        )
    except:
        logger.info(traceback.format_exc())
    return mtinfo
def getELEinfo(account):
    '''
    通过id获取饿了么信息
    :param mtid:
    :return:
    '''
    info={}
    try:
        session=Session()
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).scalar()
        if not ele:
            return  info
        session.close()
        adtime=[]
        percent = []
        try:
            adtime = eval(ele.adTime)
            percent = eval(ele.percent)
        except:
            adtime = adtime
            percent = percent
        info=dict(
            id=ele.eleId,
            name=ele.eleName,
            account=ele.account,
            shoptimestart=ele.shopTimeStart,
            shoptimeend=ele.shopTimeEnd,
            shopstatus=ele.shopStatus,
            cookies=ele.cookies,
            isbind=ele.isbind,
            budget=ele.budget,
            isenable=ele.isenable,
            isonline=ele.isonline,
            targetexposure=ele.targetExposure,
            createtime=ele.createtime,
            adtime=adtime,
            isbybudget=ele.isbybudget if ele.isbybudget else 0,
            percent=percent,
            updatetime = ele.updatetime,
            shipTime = ele.shipTime,
            specialtime = ele.specialtime,
            shopId = ele.shopId,
            salt = ele.salt,
            userName = ele.userName,
            historyCurbid = ele.historyCurbid,
            idleExposureRate = ele.shopTimeEnd,
            allExposureRate = ele.shopTimeStart,
        )
    except:
        logger.info(traceback.format_exc())
    return info


def updEleShopInfo(**kwargs):
    '''
    更新店铺信息
    :param args:
    :param kwargs:
    :return:
    '''
    try:
        account = kwargs.get("account")
        ct = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        elebudget = kwargs.get("elebudget", None)
        eleisenable = kwargs.get("eleisenable", None)
        eleid = kwargs.get("eleId")
        eleTargetExposure = kwargs.get("eletargetExposure")

        shipTime = kwargs.get("eleshiptime", '')
        adtime = kwargs.get("eleadtime", '')
        percent = kwargs.get("percent")
        specialtime = kwargs.get("specialtime")
        keepSameStatus = kwargs.get("keepSameStatus")
        serviceTime = kwargs.get("serviceTime")
        idleExposureRate = kwargs.get("idleExposureRate")
        idleOrderRateList = kwargs.get("idleOrderRateList")
        busyOrderRate = kwargs.get("busyOrderRate")
        daysAvgPrice = kwargs.get("daysAvgPrice")

        busyTimeLock = kwargs.get("busyTimeLock")
        controlRate = kwargs.get("controlRate")
        baseRate = kwargs.get("baseRate")
        nextExposureRate = kwargs.get("nextExposureRate")
        session = Session()
        ele = None
        if account:
            ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).scalar()
        elif eleid:
            ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == eleid).scalar()

        if elebudget is not None:
            ele.budget = elebudget

        try:
            temp = eval(idleOrderRateList)
            ele.orderRate = str(
                {"idleOrderRateList": idleOrderRateList, "busyOrderRate": busyOrderRate, "daysAvgPrice": daysAvgPrice})
        except:
            logger.info(traceback.format_exc())

        plan = ele.plan
        if plan:
            try:
                plan = eval(plan)
                plan["nextExposureRate"] = nextExposureRate
                plan = str(plan)
                ele.plan = plan
            except:
                logger.info(traceback.format_exc())
        else:
            plan = {}
            plan["nextExposureRate"] = nextExposureRate
            plan = str(plan)
            ele.plan = plan


        if eleisenable is not None:
            ele.isenable = eleisenable
        if idleExposureRate:
            ele.shopTimeEnd = str(idleExposureRate)
        if adtime:
            ele.adTime = adtime
        if shipTime:
            ele.shipTime = shipTime
        if eleTargetExposure:
            ele.targetExposure = eleTargetExposure

        if busyTimeLock is not None:
            ele.busyTimeLock = busyTimeLock

        ele.exposureRate = str({"controlRate": float(controlRate), "baseRate": float(baseRate)})

        if percent:
            ele.percent = percent
        if specialtime and not ele.specialtime:
            ele.specialtime = specialtime
        if serviceTime:
            ele.serviceTime = serviceTime
        if keepSameStatus is not None:
            ele.keepSameStatus = keepSameStatus
        ele.updatetime = ct
        session.commit()
        session.close()
    except:
        logger.warning(traceback.format_exc())


def updShopInfo(**kwargs):
    mtaccount = kwargs.get("mtaccount", '')
    eleaccount = kwargs.get("eleaccount", '')
    if mtaccount:
        kwargs.update(account=mtaccount)
        updShopMeituanInfo(**kwargs)
    if eleaccount:
        kwargs.update(account=eleaccount)
        updEleShopInfo(**kwargs)


def deleteTodayTarget(account, immediate):
    session = Session()
    today = None
    today_ad = None
    if immediate == 1:
        today = datetime.datetime.now().date().strftime("%Y-%m-%d") + " 00:00:00"
        today_ad = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d") + " 00:00:00"
    else:
        today = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d") + " 00:00:00"
        today_ad = (datetime.datetime.now() + datetime.timedelta(days=2)).strftime("%Y-%m-%d") + " 00:00:00"

    sql = "delete  from shop_bidding_target where  exposureTime >= '" + today + "' and exposureTime < '" + today_ad + "' and account = '" + account + "'"
    session.execute(sql)
    session.commit()
    session.close()


def setIsEnable0(account, type, para):
    session = Session()
    if type == 2:
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).scalar()

        ele.isenable = para
        session.commit()
    elif type == 1:
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()
        mt.isenable = para
        session.commit()
    session.close()


def setLowPricePlan(account, type, guard):
    session = Session()
    if type == 2:
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).scalar()
        ele.guard = guard
        session.commit()
    elif type == 1:
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()
        mt.guard = guard
        session.commit()
    session.close()


def getShopInfoNew(**kwargs):

    shopinfo = {}
    shopList = []
    invalidLogon = False
    # try:
    mtId = kwargs.get("mtId")
    eleId = kwargs.get("eleId")
    type = 1
    if eleId:
        type = 2
    today = datetime.datetime.now().date().strftime("%Y-%m-%d")

    session = Session()
    if type == 1:
        mtShop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == mtId).first()

        yesOrderInfo = session.query(YesOrderInfo).filter(YesOrderInfo.account == mtShop.account).order_by(YesOrderInfo.id.desc())[0:7]
        session.close()

        allInfoLists = [0 for i in range(0, 48)]
        for t in yesOrderInfo:
            if t.InfoList:
                t = eval(t.InfoList)
                if len(t) == 48:
                    for i in range(48):
                        allInfoLists[i] += t[i]

        allInfoLists = str(allInfoLists)
        if not yesOrderInfo:
            yesOrderInfo = [0 for i in range(0, 48)]
            yesOrderInfo = str(yesOrderInfo)
        else:
            yesOrderInfo = allInfoLists

        idleMaxPriceList = """['','','','','','','','']"""
        if mtShop.specialtime:
            idleMaxPriceList = []
            specialtime = eval(mtShop.specialtime)
            for st in specialtime:
                if not st.get("type") == 1 and st.get("p7")!= 'NaN':
                    idleMaxPriceList.append(float(st.get("p7")))
        cookies = mtShop.cookies
        idleExposureRate = mtShop.shopTimeEnd
        if idleExposureRate:
            idleExposureRate = float(idleExposureRate)
        else:
            idleExposureRate = 1.45

        todayExposureRate = 1
        if mtShop.plan:
            plan = eval(mtShop.plan)
            todayExposureRate = plan.get("nextExposureRate",1)



        mt = MTSpider(cookies)
        details = mt.getDetail(None)
        if not details:
            todayBudget = '---'
            invalidLogon = True
        else:
            todayBudget = int(details.get("budget") / 100)
        orderRate = None
        idleOrderRateList = """['','','','','','','','']"""
        busyOrderRate = ''
        daysAvgPrice = ''
        if orderRate and orderRate != "{'idleOrderRateList': '[,,,,,,,,]', 'busyOrderRate': '', 'daysAvgPrice': ''}":
            orderRate = eval(orderRate)
            idleOrderRateList = orderRate.get("idleOrderRateList")
            busyOrderRate = orderRate.get("busyOrderRate")
            daysAvgPrice = orderRate.get("daysAvgPrice")
            if busyOrderRate and idleOrderRateList:
                busyOrderRate = float(busyOrderRate)
                idleOrderRateList = eval(idleOrderRateList)
                for i in range(len(idleOrderRateList)):
                    idleOrderRateList[i] = float(idleOrderRateList[i])
        historyCurbid = mtShop.historyCurbid
        if not historyCurbid or historyCurbid.strip() == "":
            historyMode = 0
        else:
            historyCurbid = eval(historyCurbid)
            historyMode = historyCurbid.get('status')

        allExposureRate = mtShop.shopTimeStart if mtShop.shopTimeStart and mtShop.shopTimeStart != "" else 0

        controlRate = 0.3
        baseRate = 0.9
        nextExposureRate = 0
        try:
            exposureRate = mtShop.exposureRate
            if exposureRate:
                exposureRate = eval(exposureRate)
                controlRate = exposureRate.get("controlRate")
                baseRate = exposureRate.get("baseRate")
                nextExposureRate = exposureRate.get("nextExposureRate")
        except:
            logger.info(traceback.format_exc())



        shopList.append({
            "invalidLogon" : invalidLogon,
            "budget": mtShop.budget,
            "account": mtShop.account,
            "shopname": mtShop.mtName,
            "shoptype": mtShop.shopType,
            "isenable": mtShop.isenable,
            "isbind": mtShop.isbind,
            "allExposureRate" : allExposureRate,
            "isbybudget": mtShop.isbybudget,
            "adTime": mtShop.adTime,
            "targetExposure": mtShop.targetExposure,
            "specialtime": mtShop.specialtime,
            "keepSameStatus": mtShop.keepSameStatus,
            "serviceTime": mtShop.serviceTime,
            "deleted": mtShop.deleted,
            "guard": mtShop.guard,
            "historyMode": historyMode,
            "todayBudget": todayBudget,
            "lock": mtShop.isremake,
            "idleExposureRate" : idleExposureRate,
            "idleOrderRateList":idleOrderRateList,
            "busyOrderRate":busyOrderRate,
            "idleMaxPriceList" : idleMaxPriceList,
            "daysAvgPrice":daysAvgPrice,
            "busyTimeLock" : mtShop.busyTimeLock,
            "controlRate" :controlRate,
            "baseRate" :baseRate,
            "nextExposureRate" : nextExposureRate,
            "todayExposureRate" : todayExposureRate,
        })
        shopList.append(mtShop.percent)
        shopList.append(yesOrderInfo)

    else:

        eleShop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == eleId).first()
        yesOrderInfo = session.query(YesOrderInfo.InfoList).filter(YesOrderInfo.account == eleShop.account).order_by(YesOrderInfo.id.desc())[0:7]
        session.close()

        allInfoLists = [0 for i in range(0, 48)]
        for t in yesOrderInfo:
            if t and t[0]:
                t = eval(t[0])
                if len(t) == 48:
                    for i in range(48):
                        allInfoLists[i] += t[i]

        allInfoLists = str(allInfoLists)
        if not yesOrderInfo:
            yesOrderInfo = [0 for i in range(0, 48)]
            yesOrderInfo = str(yesOrderInfo)
        else:
            yesOrderInfo = allInfoLists
        cookies = eleShop.cookies
        ele = ELESpider(cookies)
        todayBudget = 0
        try:
            adPrice = ele.getAdPrice()
            todayBudget = adPrice.get("budget", 0)
        except:
            todayBudget = "---"
            invalidLogon = True

        historyCurbid = eleShop.historyCurbid
        if not historyCurbid or historyCurbid.strip() == "":
            historyMode = 0
        else:
            historyCurbid = eval(historyCurbid)
            historyMode = historyCurbid.get('status')
        idleExposureRate = eleShop.shopTimeEnd
        if idleExposureRate:
            idleExposureRate = float(idleExposureRate)
        else:
            idleExposureRate = 1.45

        idleMaxPriceList = '['', '', '', '', '', '', '', '']'
        if eleShop.specialtime:
            idleMaxPriceList = []
            specialtime = eval(eleShop.specialtime)
            for st in specialtime:
                if not st.get("type") == 1 and st.get("p7")!= 'NaN':
                    idleMaxPriceList.append(float(st.get("p7")))

        todayExposureRate = 1
        if eleShop.plan:
            plan = eval(eleShop.plan)
            todayExposureRate = plan.get("nextExposureRate", 1)


        orderRate = None
        idleOrderRateList = """"['', '', '', '', '', '', '', '']"""
        busyOrderRate = ''
        daysAvgPrice = ''
        if orderRate and orderRate != "{'idleOrderRateList': '[,,,,,,,,]', 'busyOrderRate': '', 'daysAvgPrice': ''}" and orderRate != "{'idleOrderRateList': None, 'busyOrderRate': None, 'daysAvgPrice': ''}":
            orderRate = eval(orderRate)
            idleOrderRateList = orderRate.get("idleOrderRateList")
            busyOrderRate = orderRate.get("busyOrderRate")
            daysAvgPrice = orderRate.get("daysAvgPrice")
            if busyOrderRate and idleOrderRateList:
                busyOrderRate = float(busyOrderRate)
                idleOrderRateList = eval(idleOrderRateList)

                for i in range(len(idleOrderRateList)):
                    idleOrderRateList[i] = float(idleOrderRateList[i])

        allExposureRate = eleShop.shopTimeStart if eleShop.shopTimeStart and eleShop.shopTimeStart != "" else ""

        controlRate = 0.3
        baseRate = 0.9
        nextExposureRate = 1
        try:
            exposureRate = eleShop.exposureRate
            if exposureRate:
                exposureRate = eval(exposureRate)
                controlRate = exposureRate.get("controlRate")
                baseRate = exposureRate.get("baseRate")
                nextExposureRate = exposureRate.get("nextExposureRate")
        except:
            logger.info(traceback.format_exc())


        shopList.append({
            "invalidLogon" : invalidLogon,
            "budget": eleShop.budget,
            "account": eleShop.account,
            "shopname": eleShop.eleName,
            "allExposureRate" : allExposureRate,
            "shoptype": eleShop.shopType,
            "isenable": eleShop.isenable,
            "isbind": eleShop.isbind,
            "isbybudget": eleShop.isbybudget,
            "adTime": eleShop.adTime,
            "targetExposure": eleShop.targetExposure,
            "specialtime": eleShop.specialtime,
            "keepSameStatus": eleShop.keepSameStatus,
            "serviceTime": eleShop.serviceTime,
            "deleted": eleShop.deleted,
            "guard": eleShop.guard,
            "historyMode": historyMode,
            "todayBudget": todayBudget,
            "lock": eleShop.isremake,
            "idleExposureRate" : idleExposureRate,
            "idleMaxPriceList" : idleMaxPriceList,
            "daysAvgPrice":daysAvgPrice,
            "idleOrderRateList":idleOrderRateList,
            "busyTimeLock": eleShop.busyTimeLock,
            "controlRate": controlRate,
            "baseRate": baseRate,
            "nextExposureRate" : nextExposureRate,
            "todayExposureRate" : todayExposureRate,
        })
        shopList.append(eleShop.percent)
        shopList.append(yesOrderInfo)

    return shopList
    # except:
    #     logger.error(traceback.format_exc())
    #     return 500


def getShopInfoNewWeb(shopId,shopType):

    try:
        session = Session()

        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
            yesOrderInfo = session.query(YesOrderInfo).filter(YesOrderInfo.account == shop.account).order_by(YesOrderInfo.id.desc())[0:7]
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
            yesOrderInfo = session.query(YesOrderInfo).filter(YesOrderInfo.account == shop.account).order_by(
                YesOrderInfo.id.desc())[0:7]
        session.close()

        allInfoLists = [0 for i in range(0, 48)]
        for t in yesOrderInfo:
            if t.InfoList:
                t = eval(t.InfoList)
                if len(t) == 48:
                    for i in range(48):
                        allInfoLists[i] += t[i]
        orderList1 = allInfoLists[0:12]
        orderList2 = allInfoLists[12:24]
        orderList3 = allInfoLists[24:36]
        orderList4 = allInfoLists[36:48]



        idleMaxPriceList = ['','','','','','','','']
        if shop.specialtime:
            idleMaxPriceList = []
            specialtime = eval(shop.specialtime)
            for st in specialtime:
                if not st.get("type") == 1:
                    idleMaxPriceList.append(float(st.get("p7")))

        idleExposureRate = shop.shopTimeEnd
        if idleExposureRate:
            idleExposureRate = float(idleExposureRate)
        else:
            idleExposureRate = 1.45

        orderRate = shop.orderRate
        idleOrderRateList = ['', '', '', '', '', '', '', '']
        busyOrderRate = ''
        daysAvgPrice = ''
        if orderRate:
            try:
                orderRate = eval(orderRate)
                idleOrderRateList = orderRate.get("idleOrderRateList")
                busyOrderRate = orderRate.get("busyOrderRate")
                daysAvgPrice = float(orderRate.get("daysAvgPrice")) if orderRate.get(
                    "daysAvgPrice") is not None and orderRate.get("daysAvgPrice") != '' else ''
                if busyOrderRate :
                    busyOrderRate = float(busyOrderRate)
                if idleOrderRateList:
                    idleOrderRateList = eval(idleOrderRateList)
                    for i in range(len(idleOrderRateList)):
                        idleOrderRateList[i] = float(idleOrderRateList[i])

            except:
                idleOrderRateList = ['', '', '', '', '', '', '', '']
                logger.info(traceback.format_exc())

        historyCurbid = shop.historyCurbid
        if not historyCurbid or historyCurbid.strip() == "":
            historyMode = 0
        else:
            historyCurbid = eval(historyCurbid)
            historyMode = historyCurbid.get('status')

        allExposureRate = float(shop.shopTimeStart) if shop.shopTimeStart is not None and shop.shopTimeStart != "" else 0

        controlRate = 0.3
        baseRate = 0.9
        nextExposureRate = 1
        try:
            exposureRate = shop.exposureRate
            if exposureRate:
                exposureRate = eval(exposureRate)
                controlRate = exposureRate.get("controlRate")
                baseRate = exposureRate.get("baseRate")
                nextExposureRate = exposureRate.get("nextExposureRate")
                if nextExposureRate is None or nextExposureRate == '0' or nextExposureRate == '':
                    nextExposureRate = 1

        except:
            logger.info(traceback.format_exc())

        todayExposureRate = 1
        if shop.plan:
            plan = eval(shop.plan)
            todayExposureRate = plan.get("nextExposureRate")
            if todayExposureRate is None or todayExposureRate == '0' or todayExposureRate == '':
                todayExposureRate = 1

        adTime = eval(shop.adTime)
        adTimeList = []
        for at in adTime:
            sh = int(at.get("s").split(":")[0])
            sm = int(at.get("s").split(":")[1])
            eh = int(at.get("e").split(":")[0])
            em = int(at.get("e").split(":")[1])
            adTimeList.append({"sh":sh,"sm":sm,"eh":eh,"em":em})


        idleMinPrice = ""
        busyMaxPrice = ""
        busyMinPrice = ""
        percent = ""
        idleInfoList = []
        busyInfoList = []
        specialtime = eval(shop.specialtime)
        for st in specialtime:
            if st.get("type") == 1:
                busyMaxPrice = st.get("p7")
                busyMinPrice = st.get("p6")
                percent = st.get("rate")
                busyInfoList.append(st.get("s") + "-" + st.get("e"))
            else:
                idleMinPrice = st.get("p6")
                idleInfoList.append(st.get("s") + "-" + st.get("e"))
                percent = st.get("rate")
        return {
            "budget": int(float(shop.budget)),
            "account": shop.account,
            "shopname": shop.mtName if shopType == 1 else shop.eleName,
            "shoptype": shop.shopType,
            "isenable": shop.isenable,
            "allExposureRate" : allExposureRate,
            "adTimeList": adTimeList,
            "shipTime" : shop.shipTime,
            "createTime" : shop.createtime,
            "lastEditTime" : shop.updatetime,
            "targetExposure": shop.targetExposure,
            "guard": shop.guard,
            "historyMode": historyMode,
            "lock": shop.isremake,
            "idleExposureRate" : idleExposureRate,
            "idleOrderRateList":idleOrderRateList,
            "busyOrderRate":busyOrderRate,
            "idleMaxPriceList" : idleMaxPriceList,
            "daysAvgPrice" : daysAvgPrice,
            "busyTimeLock" : shop.busyTimeLock,
            "controlRate" :controlRate,
            "baseRate" :baseRate,
            "idleInfoList":idleInfoList,
            "busyInfoList":busyInfoList,
            "orderList1": orderList1,
            "orderList2": orderList2,
            "orderList3": orderList3,
            "orderList4": orderList4,
            "nextExposureRate":float(nextExposureRate),
            "todayExposureRate":float(todayExposureRate),
            "idleMinPrice": float(idleMinPrice),
            "busyMaxPrice":float(busyMaxPrice),
            "busyMinPrice":float(busyMinPrice),
            "percent":float(percent),
        }
    except:
        logger.error(traceback.format_exc())
        return 500


def formatInfoList(infoList, mins):
    outInfoList = []
    i = 0
    j = mins
    while i < 24:
        while j <= 60:
            if j == 60:
                j = 0
                break
            else:
                t = "%02d:%02d" % (i, j)
                outInfoList.append({'date': t, 'orderNum': 0})
                j += mins
        i += 1
    outInfoList.append({'date': "23:59", 'orderNum': 0})
    for i in range(0, int(60 / mins) * 24):
        outInfoList[i]['orderNum'] += infoList[i]
    return outInfoList


def getAdtime(account, type=1):
    '''
    获取美团饿了么推广时间段
    :param mteleId:
    :param type:
    :return:
    '''
    adtime = None
    session = Session()
    if type == 1:
        adtime = session.query(ShopMeituanInfo.adTime).filter(ShopMeituanInfo.account == account).scalar()
    else:
        adtime = session.query(ShopEleInfo.adTime).filter(ShopEleInfo.account == account).scalar()
    session.close()
    return adtime


def getTargetBidding(account, type=1):
    session = Session()
    dt = (datetime.datetime.now().date() + datetime.timedelta(days=0)).strftime("%Y-%m-%d") + " 00:00:00"
    tomorrow = (datetime.datetime.now().date() + datetime.timedelta(days=1)).strftime("%Y-%m-%d") + " 00:00:00"

    sql = session.query(ShopBiddingTarget.id, ShopBiddingTarget.account, ShopBiddingTarget.exposureNum,
                        ShopBiddingTarget.exposureTime,
                        ShopBiddingTarget.newExposureNum,
                        ShopBiddingTarget.type, ShopBiddingTarget.isbybudget, ShopBiddingTarget.periodtarget,
                        ShopBiddingTarget.budget).filter(
        ShopBiddingTarget.account == account,
        ShopBiddingTarget.type == type, ShopBiddingTarget.exposureTime >= dt, ShopBiddingTarget.exposureTime < tomorrow)

    rows = sql.all()

    rows2 = session.query(ShopBiddingTarget.id, ShopBiddingTarget.account, ShopBiddingTarget.exposureNum,
                          ShopBiddingTarget.exposureTime,
                          ShopBiddingTarget.newExposureNum,
                          ShopBiddingTarget.type, ShopBiddingTarget.isbybudget, ShopBiddingTarget.periodtarget,
                          ShopBiddingTarget.budget).filter(
        ShopBiddingTarget.account == account,
        ShopBiddingTarget.type == type, ShopBiddingTarget.exposureTime >= tomorrow).all()
    session.close()
    result = []
    retrows = []
    tomorrows = []
    for r in rows:
        id, account, num, etime, newnum, tp, isbybudget, periodtarget, budget = r
        retrows.append(dict(id=id, account=account, exposurenum=num, exposuretime=etime, newexposurenum=newnum, type=tp,
                            isbybudget=isbybudget, budget=budget))
    result.append(retrows)
    for r in rows2:
        id, account, num, etime, newnum, tp, isbybudget, periodtarget, budget = r
        tomorrows.append(
            dict(id=id, account=account, exposurenum=num, exposuretime=etime, newexposurenum=newnum, type=tp,
                 isbybudget=isbybudget, budget=budget))
    result.append(tomorrows)
    return result


def getTargetExposure(account, type=1):
    '''
    获取美团或者饿了么目标曝光量
    :param mtEleId:
    :param type:1 mt,2 ele
    :return:
    '''
    mtnum = elenum = num = 0
    mtaccount = ''
    eleaccount = ''
    session = Session()

    if type == 1:
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()
        if mt:  # and mt.targetExposure:
            num = mt.targetExposure
        # elif mt and mt.account:
        #     num = session.query(ShopInfo.targetExposure).filter(ShopInfo.mtaccount==account).scalar()


    else:
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).scalar()
        if ele:  # and ele.targetExposure:
            num = ele.targetExposure
        # elif ele and ele.account:
        #     num = session.query(ShopInfo.targetExposure).filter(ShopInfo.mtaccount == account).scalar()

    if not num: num = 0
    session.close()
    return num


def delTargetExposure(account, type, isnomarl=True):
    '''
    设置推广计划前删除旧的计划
    :param account:
    :param type:
    :param ct:
    :param isnomarl:
    :return:
    '''
    try:
        logger.debug('account:{},type:{}'.format(account, type))
        if not isnomarl:
            session = Session()
            sql = "delete from shop_bidding_target where account='{}' and type={} and date(exposureTime)>sysdate();".format(
                account, type)
            logger.debug(sql)
            session.execute(sql)
            session.commit()
            session.close()
    except:
        logger.warning(traceback.format_exc())


def setNewExposureNum0(account, type, start):
    try:
        session = Session()
        plans = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.exposureTime > start,
                                                        ShopBiddingTarget.account == account).all()
        if plans:
            for plan in plans:
                plan.newExposureNum = 0

        session.commit()
        session.close()
    except:
        logger.warning(traceback.format_exc())


def updTargetExposure(account, type, ct, num, budget, shopId):
    '''
    更新插入目标曝光值
    :param account:
    :param type:
    :param ct:
    :param num:
    :param isbybudget:
    :param isnomarl: 是否是人工生成
    :return:
    '''
    try:
        session = Session()
        # 直接添加
        session.add(ShopBiddingTarget(
            account=account,
            exposureNum=num,
            budget=budget,
            exposureTime=ct,
            type=type,
            shopid=shopId
        ))
        session.commit()
        session.close()
    except:
        logger.warning(traceback.format_exc())


def updAllShopBiddingTarget(all_plans):
    '''
    插入多条计划
    :param all_plans:
    :return:
    '''
    try:
        session = Session()
        # 直接添加
        session.add_all(all_plans)
        result = session.commit()
        session.close()
    except:
        logger.warning(traceback.format_exc())


def getHourTargetExposure(account, ct, dt_ad, type=1):
    try:
        session = Session()
        shopBiddingTarget = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.account == account,
                                                                    ShopBiddingTarget.type == type,
                                                                    or_(ShopBiddingTarget.exposureTime == ct,
                                                                        ShopBiddingTarget.exposureTime == dt_ad)).first()
        session.close()
        if not shopBiddingTarget:
            target = 0
            budget = 0
        else:
            target = shopBiddingTarget.exposureNum
            budget = shopBiddingTarget.budget
        return {"target": target, "budget": budget}
    except:
        print(traceback.format_exc())
        logger.warning(traceback.format_exc())





def getShopBiddingReplenishNum(shopid, today, type):
    '''
    获取补偿曝光量
    :return:
    '''
    try:
        session = Session()
        shopBidding = session.query(ShopBidding).filter(ShopBidding.shopid == shopid, ShopBidding.biddingTime >= today,
                                                        ShopBidding.shoptype == type, ).order_by(
            ShopBidding.id.desc()).first()
        session.close()
        return shopBidding
    except:
        logger.warning(traceback.format_exc())


def updShopBidding(*args, **kwargs):
    try:
        shopid, ct, shoptype = args
        targetNum = kwargs.get("targetNum", 0)
        exposureNum = kwargs.get("exposureNum", 0)
        basePrice = kwargs.get("basePrice", 0)
        directPrice = kwargs.get("directPrice", 0)
        log = kwargs.get("log", '')
        blance = kwargs.get("blance", 0)
        replenishnum = kwargs.get("replenishnum", 0)
        isbybudget = kwargs.get("isbybudget", 0)
        status = kwargs.get("status", 0)
        visitNum = kwargs.get("visitNum", 0)
        todayBudget = kwargs.get("todayBudget", 0)
        exLog = kwargs.get("exLog", '')
        periodtarget = kwargs.get("periodtarget", 0)
        periodexposure = kwargs.get("periodexposure", 0) if kwargs.get("periodexposure", 0) >= 0 else 0
        realTimeOrder = kwargs.get("realTimeOrder", 0) if kwargs.get("realTimeOrder", 0) != None else 0
        allExposure = kwargs.get("allExposure", 0) if kwargs.get("allExposure", 0) != None else 0
        businessAmount = kwargs.get("income", 0) if kwargs.get("income", 0) != None else 0
        percentBudget = kwargs.get("percentBudget", 0)
        currentCost = kwargs.get("currentCost", 0) if kwargs.get("currentCost", 0) != None else 0
        setPrice = kwargs.get("setPrice", 0)
        session = Session()
        b = session.query(ShopBidding).filter(ShopBidding.biddingTime == ct, ShopBidding.shopid == shopid,
                                              ShopBidding.shoptype == shoptype).scalar()
        if not b:
            session.add(
                ShopBidding(
                    shopid=shopid,
                    biddingTime=ct,
                    targetNum=targetNum,
                    exposureNum=exposureNum,
                    basePrice=basePrice,
                    directPrice=directPrice,
                    log=log,
                    exLog=exLog,
                    status=status,
                    blance=blance,
                    shoptype=shoptype,
                    createtime=datetime.datetime.now(),
                    visitNum=visitNum,
                    todayBudget=todayBudget,
                    periodexposure=periodexposure,
                    periodtarget=periodtarget,
                    replenishNum=replenishnum,
                    businessAmount=businessAmount,
                    allExposure=allExposure,
                    realTimeOrder=realTimeOrder,
                    percentBudget=percentBudget,
                    currentCost=currentCost,
                    setPrice=setPrice,
                    isbybudget=isbybudget)
            )
        else:
            if targetNum != None:
                b.targetNum = targetNum
            if exposureNum != None:
                b.exposureNum = exposureNum
            if basePrice != None:
                b.basePrice = basePrice
            if directPrice != None:
                b.directPrice = directPrice
            if log != None:
                b.log = log
            if exLog != None:
                b.exLog = exLog
            if blance != None:
                b.blance = blance
            if periodexposure != None:
                b.periodexposure = periodexposure
            if periodtarget != None:
                b.periodtarget = periodtarget
            if businessAmount != None:
                b.businessAmount = businessAmount
            if allExposure != None:
                b.allExposure = allExposure
            if realTimeOrder != None:
                b.realTimeOrder = realTimeOrder
            if todayBudget != None:
                b.todayBudget = todayBudget
            if percentBudget != None:
                b.percentBudget = percentBudget
            if currentCost != None:
                b.currentCost = currentCost
            if replenishnum != None:
                b.replenishNum = b.replenishNum + replenishnum
            if status != None:
                b.status = status
            if setPrice != None:
                b.setPrice = setPrice
            if visitNum != None:
                b.visitNum = visitNum
        session.commit()
        session.close()
    except:
        logger.warning(traceback.format_exc())


def setShopCurbid(shopId, shopType):
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId, ShopEleInfo.shopType == shopType).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId,
                                               ShopMeituanInfo.shopType == shopType).first()
    cookies = ''
    if ele:
        cookies = ele.cookies
        ele = ELESpider(cookies)
    elif mt:
        cookies = mt.cookies
        mt = MTSpider(cookies)


def getTodayTarget(account):
    '''
    查看今天有没有推广计划
    :param account:
    :return:
    '''
    a = func.date(ShopBiddingTarget.exposureTime)
    b = datetime.datetime.now().date()
    try:
        session = Session()
        target = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.account == account, func.date(
            ShopBiddingTarget.exposureTime) == datetime.datetime.now().date()).first()
        session.close()
        return target

    except:
        logger.warning(traceback.format_exc())
        return False


def getAllmtShop4Spider():
    '''
    获得全部美团商铺信息
    :return:
    '''

    session = Session()
    # sql=session.query(ShopMeituanInfo.account,ShopMeituanInfo.cookies,ShopMeituanInfo.shipTime,ShopMeituanInfo.adTime).filter(ShopMeituanInfo.deleted==0,
    #                                                                                                                            ShopMeituanInfo.isenable==1,
    #
    #                                                                                                                  ShopMeituanInfo.cookies!='',
    #                                                                                                                  ShopMeituanInfo.isbind==1)#.all()
    sql = '''    
        select m.account,m.cookies,m.shipTime,m.adTime,m.isbybudget,m.guard from user u
        right join user_shop_relation r
        on u.id=r.userId
        right join shop_info s
        on r.shopId=s.id
        left join shop_meituan_info m
        on s.mtaccount=m.account
        where  m.deleted=0
        and m.isenable=1
        and m.cookies!=''
            '''
    logger.debug(sql)
    rows = session.execute(sql).fetchall()
    session.close()
    return rows


def getAlleleShop4Spider():
    '''
    获取全部饿了么商铺信息
    :return:
    '''
    session = Session()
    # rows = session.query(ShopEleInfo.account, ShopEleInfo.cookies,ShopEleInfo.shipTime,ShopEleInfo.adTime).filter(ShopEleInfo.deleted == 0,ShopEleInfo.isenable==1,ShopEleInfo.cookies !='',ShopEleInfo.isbind==1).all()
    sql = '''
            select m.account,m.cookies,m.shipTime,m.adTime,m.isbybudget,m.guard from user u
            right join user_shop_relation r
            on u.id=r.userId
            right join shop_info s
            on r.shopId=s.id
            left join shop_ele_info m
            on s.eleaccount=m.account
            where  m.deleted=0
            and m.isenable=1
            and m.cookies!=''
            and m.isbind=1
                '''
    logger.debug(sql)
    rows = session.execute(sql).fetchall()
    session.close()
    return rows


def myMd5(ctime, data):
    '''
    md5加密
    :param ctime:当前时间戳，用于加密因子使用
    :param data: 加密的数据
    :return: 加密后的数据
    '''
    m = hashlib.md5(bytes(data, encoding='utf-8'))  # MD5接收字节类型数据，中文先用utf-8加密
    m.update(bytes(ctime, encoding='utf-8'))  # 使用当前的时间加密，如不加这MD5是不安全的(每次生成的加密序列都一样)
    return m.hexdigest()  # 输出加密的对象  hex(十六进制) + digest(摘要) -> hexdigest


def updMtCookie(mtaccount, mtcookie):
    '''
    更新美团cookie
    :param mtaccount:
    :param mtcookie:
    :return:
    '''
    try:
        if not mtaccount:
            logger.info("mtaccount is null")
            return
        mtid = ''
        for c in mtcookie.split(";"):
            try:
                k, v = c.split('=')
                k = k.strip()
                v = v.strip()
                if k == 'wmPoiId':
                    mtid = v
            except:
                logger.debug(c)
                continue
        if not mtid:
            logger.info('mtid is null')
            return
        session = Session()
        mtinfo = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == mtaccount).first()
        if not mtinfo:
            logger.info("shop is null")
        elif not mtinfo.mtId:
            mtinfo.mtId = mtid
            mtinfo.cookies = mtcookie
        elif str(mtinfo.mtId) == (mtid):
            mtinfo.cookies = mtcookie
        else:
            logger.info("mtid is Inequality")
        if mtinfo.shopId == '' or mtinfo.shopId == None:
            ctime = str(time.time())
            shopId = myMd5(ctime, mtid)
            mtinfo.salt = ctime
            mtinfo.shopId = shopId

        session.commit()
        session.close()
        return True
    except:
        logger.warning(traceback.format_exc())
        return


def updeleCookie(account, ksid, shopid):
    '''
    更新ele cookie
    :param mtaccount:
    :param mtcookie:
    :return:
    '''
    try:
        if not account:
            logger.info("eleaccount is null")
            return
        if not ksid:
            logger.info('ksid is null')
            return
        if not shopid:
            logger.info('eleid is null')
            return
        cookie = 'eleshopid={}; eleksid={}; account={}'.format(shopid, ksid, account)
        session = Session()
        info = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()
        if not info:
            logger.info("eleshop is null")
        elif not info.eleId:
            info.eleId = shopid
            info.cookies = cookie
        else:
            logger.info("eleid is Inequality")
        if not info.shopId:
            ctime = str(time.time())
            shopId = myMd5(ctime, shopid)
            info.salt = ctime
            info.shopId = shopId
        if shopid and account:
            shopEleInfo = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()
            if shopEleInfo:
                shopEleInfo.cookies = cookie
        session.commit()
        session.close()
        return True

    except:
        logger.warning(traceback.format_exc())
        return


def addDaysFromPay(*args, **kwargs):
    '''
    用户支付后增加天数
    :return:
    '''
    resp = {}
    try:

        openId, adddays = args
        adddays = int(adddays)
        pay_no = kwargs.get("pay_no", 0)
        session = Session()
        if not pay_no:
            logger.info("pay_no:{} !!!".format(pay_no))
            resp = dict(code=500, message="pay_no 为空", data='')
            return resp

        pay = session.query(UserInvitationPayDetail).filter(UserInvitationPayDetail.pay_no == pay_no).scalar()
        if pay:
            logger.info("pay_no:{} is exists!".format(pay_no))
            resp = dict(code=403, message="pay_no:{} is exists!", data='')
            return resp
        user = session.query(User).filter(User.openId == openId).scalar()
        if user:
            userid = user.id
            user.expiretime = user.expiretime + adddays * 24 * 60 * 60
            session.add(UserInvitationPayDetail(
                userId=userid,
                pay_no=pay_no,
                addtype=2,
                adddays=int(adddays),
                createtime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ))
            session.commit()
            try:
                masterid = session.query(UserInvitationPayDetail.userId).filter(
                    UserInvitationPayDetail.slaveid == userid).scalar()
                if masterid:
                    masteruser = session.query(User).filter(User.id == masterid).scalar()
                    if masteruser:
                        if int(masteruser.expiretime) < int(time.time()):
                            masteruser.expiretime = int(time.time()) + int(adddays) * 24 * 60 * 60
                        else:
                            masteruser.expiretime = masteruser.expiretime + adddays * 24 * 60 * 60
                        session.commit()
            except:
                logger.warning(traceback.format_exc())
            logger.info("userid:{} pay success,add {},pay_no:{}!".format(userid, adddays, pay_no))

        else:
            logger.warning('no user')
        session.close()
        return dict(code=200, message="", data='')
    except:
        logger.warning(traceback.format_exc())
        return dict(code=500, message="fail", data=traceback.format_exc())


# def expireUser():
#     session=Session()
#     userids=session.query(User.id).filter(User.expiretime<=int(time.time())).all()
#     for u in userids:
#         session.query()
def getMidExposure(beginExposure, endExposure, cutTimeStamp, lengthStamp):
    '''
    获取小时内的预期曝光量
    :param beginExposure:
    :param endExposure:
    :param cutTimeStamp:
    :return:
    '''
    if cutTimeStamp == 0 or endExposure == beginExposure:
        return beginExposure
    return (endExposure - beginExposure) / lengthStamp * cutTimeStamp + beginExposure


def getPreviousExposure(shopid, bTime, eTime, nowExposure):
    '''
    计算现在是否需要发送通知反馈给用户曝光量情况（主要是看是否正常）
    :param account: 账号
    :param bTime: 前一个时间
    :param eTime: 后一个时间
    :param nowExposure: 当前的曝光量
    :return:
    '''
    try:
        session = Session()
        shopBidding = session.query(ShopBidding).filter(ShopBidding.shopid == shopid,
                                                        or_(ShopBidding.biddingTime == bTime,
                                                            ShopBidding.biddingTime == eTime)).first()
        session.close()
        if shopBidding:
            if nowExposure <= shopBidding.exposureNum + config.CUT_EXPOSURE:
                return True
        return False
    except:
        print(traceback.format_exc())
        logger.warning(traceback.format_exc())



def getShopStatus(account, type):
    try:
        session = Session()
        if type == 1:
            shopInfo = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()
        else:
            shopInfo = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).scalar()
        if shopInfo:
            return shopInfo.isenable
        return None
    except:
        logger.warning(traceback.format_exc())


def delmtTargetexposurePer4Web(account, type):
    '''
    删除当天的目标曝光值
    :param account:
    :param type:
    :return:
    '''
    dt = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    session = Session()
    shopBiddingTarget = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.exposureTime > dt,
                                                                ShopBiddingTarget.account == account)
    if shopBiddingTarget:
        for shopbidding in shopBiddingTarget:
            delTarget = session.query(ShopBiddingTarget).get(shopbidding.id)
            session.delete(delTarget)
    session.commit()
    session.close()
    return True


def getAllmtShop():
    '''
    获取所有的美团店铺信息
    :return:
    '''


def updYseOrderInfo(account, infoList, today, ct):
    '''
    添加最新的昨日订单信息
    :param account:
    :param infoList:
    :param ct:
    :return:
    '''
    try:
        session = Session()
        nowOrderInfo = session.query(YesOrderInfo).filter(YesOrderInfo.account == account,
                                                          YesOrderInfo.day == today).first()
        if nowOrderInfo:
            nowOrderInfo.InfoList = str(infoList)
            nowOrderInfo.updatetime = ct
            session.commit()
            session.close()
        else:
            session.add(YesOrderInfo(
                account=account,
                InfoList=str(infoList),
                day=today,
                updatetime=ct,
            ))
            session.commit()
            session.close()
    except:
        logger.warning(traceback.format_exc())
        return dict(code=500, message="fail", data=traceback.format_exc())


def getShopCookie(account, type):
    session = Session()
    if type == 2:
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).scalar()
        if ele.cookies != '':
            return ele.cookies
        else:
            return False
    elif type == 1:
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()
        if mt.cookies != '':
            return mt.cookies
        else:
            return False


def getYesOrderInfo(account):
    '''
    获取订单信息
    :param account:
    :return:
    '''
    try:
        session = Session()
        infiList = session.query(YesOrderInfo.InfoList).filter(YesOrderInfo.account == account).order_by(
            YesOrderInfo.id.desc())[0:7]
        session.close()
        if infiList:
            return infiList
        else:
            return []
    except:
        logger.warning(traceback.format_exc())
        return dict(code=500, message="fail", data=traceback.format_exc())


def avgEleInfoList(infoLists, mins):
    outInfoList = []
    if mins == 30:
        i = 0
        j = 30
        while i < 24:
            while j <= 60:
                if j == 60:
                    j = 0
                    break
                else:
                    t = "%02d:%02d" % (i, j)
                    outInfoList.append({'date': t, 'orderNum': 0})
                    j += 30
            i += 1
        outInfoList.append({'date': "23:59", 'orderNum': 0})
        for i in range(0, 48):
            outInfoList[i]['orderNum'] += infoLists[i]
    return outInfoList


def avgInfoList(infoLists):
    '''
    将获取到的多日订单量进行平均计算
    :param infoLists:
    :return:
    '''
    yesOrderInfo = YesOrderInfo()
    outInfoList = []
    infoList = eval(infoLists[0][0])
    for info in infoList:
        outInfoList.append({'date': info.get("date"), 'orderNum': 0})
    for infoList in infoLists:
        infoList = eval(infoList[0])
        for k in range(0, len(infoList)):
            outInfoList[k]['orderNum'] += infoList[k].get("orderNum")
    numDay = len(infoLists)
    for k in range(0, len(outInfoList)):
        outInfoList[k]['orderNum'] = int(outInfoList[k]['orderNum'] / numDay)

    return outInfoList


def new_getOrderNum(beginTime, endTime, orderNum, seconds):
    '''一次函数计算订单量'''
    beginTime = int(time.mktime(time.strptime(beginTime, '%Y-%m-%d %H:%M:%S')))
    endTime = int(time.mktime(time.strptime(endTime, '%Y-%m-%d %H:%M:%S')))
    return (endTime - beginTime) / seconds * orderNum


def getOrderNum(beginTime, endTime, orderNum):
    '''一次函数计算订单量'''
    beginTime = int(time.mktime(time.strptime(beginTime, '%Y-%m-%d %H:%M:%S')))
    endTime = int(time.mktime(time.strptime(endTime, '%Y-%m-%d %H:%M:%S')))
    return (endTime - beginTime) / 3600 * orderNum


def getTuiList(adTime, today):
    '''
    获取开始时间与结束时间的列表
    :param adTime:
    :return:
    '''
    backList = []
    try:
        adTime = eval(adTime)
    except:
        adTime = adTime
    for ad in adTime:
        adList = []
        adList.append(today + " " + ad.get("s") + ":00")
        adList.append(today + " " + ad.get("e") + ":00")
        adList.append(ad.get("p", 1))
        backList.append(adList)
    return backList


def updYseOrderDetail(account, orderDetail, today, ct):
    '''
    添加最新的昨日订单信息
    :param account:
    :param infoList:
    :param ct:
    :return:
    '''
    try:
        yesOrderInfo = YesOrderInfo()
        yesOrderInfo.account = account
        yesOrderInfo.orderDetail = str(orderDetail)
        yesOrderInfo.day = today
        yesOrderInfo.updatetime = ct
        session = Session()
        nowOrderInfo = session.query(YesOrderInfo).filter(YesOrderInfo.account == account,
                                                          YesOrderInfo.day == today).first()
        if nowOrderInfo:
            nowOrderInfo.orderDetail = str(orderDetail)
            nowOrderInfo.updatetime = ct
            session.commit()
            session.close()
        else:
            session.add(yesOrderInfo)
            session.commit()
            session.close()
    except:
        logger.warning(traceback.format_exc())
        return dict(code=500, message="fail", data=traceback.format_exc())


def updYseOrderInfo(account, infoList, today, ct):
    '''
    添加最新的昨日订单信息
    :param account:
    :param infoList:
    :param ct:
    :return:
    '''
    try:
        yesOrderInfo = YesOrderInfo()
        yesOrderInfo.account = account
        yesOrderInfo.InfoList = str(infoList)
        yesOrderInfo.day = today
        yesOrderInfo.updatetime = ct
        session = Session()
        nowOrderInfo = session.query(YesOrderInfo).filter(YesOrderInfo.account == account,
                                                          YesOrderInfo.day == today).first()
        if nowOrderInfo:
            nowOrderInfo.InfoList = str(infoList)
            nowOrderInfo.updatetime = ct
            session.commit()
            session.close()
        else:
            session.add(yesOrderInfo)
            session.commit()
            session.close()
    except:
        logger.warning(traceback.format_exc())
        return dict(code=500, message="fail", data=traceback.format_exc())


def getShopInfoByShopId(sId, type):
    '''
    获取美团或者饿了么的店铺信息
    :param sId: 店铺的id
    :param type: 店铺的种类   1是美团，2是饿了么
    :return:
    '''
    shopInfo = {"id": sId, "cookies": None, "account": None}
    session = Session()
    if type == 1:
        shopInfo['cookies'], shopInfo['account'] = session.query(ShopMeituanInfo.cookies,
                                                                 ShopMeituanInfo.account).filter(
            ShopMeituanInfo.cookies != '', ShopMeituanInfo.mtId == sId).scalar()
    else:
        shopInfo['cookies'], shopInfo['account'] = session.query(ShopEleInfo.cookies, ShopEleInfo.account).filter(
            ShopEleInfo.cookies != '', ShopEleInfo.eleId == sId).scalar()
    session.close()
    if shopInfo:
        return shopInfo
    else:
        return False


def getYesOrderList(spideObj, account, mins, type, today=None, ct=None, yesstart=None, yesend=None):
    '''

    :param mt:
    :param type:
    :return:
    '''
    if type == 1:
        yestodayNum = spideObj.get_historyOrder()
        if len(yestodayNum) != 0:
            yestodayNum.sort()
            timelst = []
            for order in yestodayNum:
                # 2019-10-01 21:22:09,返回的时间是这样的，只取21:22:09
                timelst.append(order.split(' ')[1])
            dayperiod = {}
            i = 0
            j = 15
            index = 0
            a = 0
            while i < 24:
                while j <= 60:
                    if j == 60:
                        j = 0
                        break
                    else:
                        t = "%02d:%02d:00" % (i, j)
                        dayperiod[t] = 0
                        while index < len(timelst) and timelst[index] < t:
                            dayperiod[t] = dayperiod[t] + 1
                            index += 1
                        j += 15
                i += 1
            dayperiod["23:59:59"] = 0
            for tl in timelst:
                if tl > '23:45:00' and tl <= '23:59:59':
                    a += 1
            dayperiod["23:59:59"] = a

            orderList = []  # 目前orderlist是96个
            for key, value in dayperiod.items():
                orderList.append(value)

            periodOrderList = []
            index = 0
            if mins == 30:
                # 将俩个俩个相加，变成48个
                while index <= 94:
                    periodOrderList.append(orderList[index] + orderList[index + 1])
                    index += 2
            elif mins == 60:
                while index <= 92:
                    periodOrderList.append(
                        orderList[index] + orderList[index + 1] + orderList[index + 2] + orderList[index + 3])
                    index += 4
            elif mins == 15:
                periodOrderList = orderList[:]

            updYseOrderInfo(account, periodOrderList, today, ct)
            return True
    else:
        yestodayNum = spideObj.getAllOrder(yesstart, yesend, 200)

        timelst = []
        if yestodayNum:
            # 所有下单时间存进列表

            for order in yestodayNum:
                # 2019-10-01T21:22:09,返回的时间是这样的，只取21:22:09
                timelst.append(order.get("activeTime").split('T')[1])
            timelst.sort()
            dayperiod = {}
            i = 0
            j = 15
            index = 0
            a = 0
            while i < 24:
                while j <= 60:
                    if j == 60:
                        j = 0
                        break
                    else:
                        t = "%02d:%02d:00" % (i, j)
                        dayperiod[t] = 0
                        while index < len(timelst) and timelst[index] < t:
                            dayperiod[t] = dayperiod[t] + 1
                            index += 1
                        j += 15
                i += 1
            dayperiod["23:59:59"] = 0
            for tl in timelst:
                if tl > '23:45:00' and tl <= '23:59:59':
                    a += 1
            dayperiod["23:59:59"] = a

            orderList = []  # 目前orderlist是96个
            for key, value in dayperiod.items():
                orderList.append(value)

            periodOrderList = []
            index = 0
            if mins == 30:
                # 将俩个俩个相加，变成48个
                while index <= 94:
                    periodOrderList.append(orderList[index] + orderList[index + 1])
                    index += 2
            elif mins == 60:
                while index <= 92:
                    periodOrderList.append(
                        orderList[index] + orderList[index + 1] + orderList[index + 2] + orderList[index + 3])
                    index += 4
            elif mins == 15:
                periodOrderList = orderList[:]
            updYseOrderInfo(account, periodOrderList, today, ct)
            return True


def adminLogin(username, password):
    session = Session()
    admin = session.query(Admin).filter(Admin.userName == username).first()
    # print(count)
    if not admin:
        return '账号不存在'
    else:
        # admin = session.query(Admin).filter(Admin.userName == username).first()
        if admin.password == password:
            return admin.bid
        else:
            return '密码不正确'
    pass


def adminSign(username, password):
    salt = str(time.time())
    bid = myMd5(salt, username)
    session = Session()
    try:
        admin_search = session.query(Admin.id).filter(Admin.userName == username).first()
        if admin_search:
            return False
        admin = Admin(
            userName=username,
            password=password,
            salt=salt,
            bid=bid
        )
        session.add(admin)
        session.commit()
        return True
    except:
        session.rollback()
    session.close()


def decryptShopId(shopId, shopType):
    '''
    获取解密的shopID
    :param shopId:
    :param shopType:
    :return:
    '''
    shopDecryptId = None
    try:
        session = Session()
        if shopType == 1:
            shopDecryptId = session.query(ShopMeituanInfo.mtId).filter(ShopMeituanInfo.shopId == shopId).scalar()
            session.close()
        elif shopType == 2:
            shopDecryptId = session.query(ShopEleInfo.eleId).filter(ShopEleInfo.shopId == shopId).scalar()
            session.close()
        if shopDecryptId:
            return shopDecryptId
        else:
            return 1000
    except:
        return False
    finally:
        session.close()

def decryptShopIdwithsession(session,shopId, shopType):
    '''
    获取解密的shopID
    :param shopId:
    :param shopType:
    :return:
    '''
    shopDecryptId = None
    try:
        if shopType == 1:
            shopDecryptId = session.query(ShopMeituanInfo.mtId).filter(ShopMeituanInfo.shopId == shopId).scalar()
        elif shopType == 2:
            shopDecryptId = session.query(ShopEleInfo.eleId).filter(ShopEleInfo.shopId == shopId).scalar()
        if shopDecryptId:
            return shopDecryptId
        else:
            return 1000
    except:
        return False








def setShopPrice(shopType, shopId, price):
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).first()
    session.close()

    try:
        if ele:
            cookies = ele.cookies
            eleSpider = ELESpider(cookies)
            eleSpider.setBaseprice(int(price * 100))
        elif mt:

            cookies = mt.cookies
            mtSpider = MTSpider(cookies)
            mtSpider.setBaseprice(int(price * 100))

        return True
    except:
        return False


def closeShopBidding(shopId, shopType):
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).first()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).first()
    session.close()
    try:
        if ele:
            cookies = ele.cookies
            account = ele.account
            eleSpider = ELESpider(cookies)
            eleSpider.changeAdstatus(1)
            setIsEnable0(account, int(shopType), 0)
        elif mt:

            cookies = mt.cookies
            account = mt.account
            mtSpider = MTSpider(cookies)
            mtSpider.changeAdstatus(1)
            setIsEnable0(account, int(shopType), 0)

        return True
    except:
        return False



def getShopsInfo(shopId, shopType):
    '''
    获取店铺的基本信息
    :param shipId:
    :param shopType:
    :return:
    '''
    session = Session()
    shopInfo = {}
    eleShop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
    mtShop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    session.close()
    if eleShop:
        shopInfo['isEnable'] = eleShop.isenable
        shopInfo['targetExposure'] = eleShop.targetExposure
        shopInfo['budget'] = eleShop.budget
        shopInfo['adTime'] = eleShop.adTime
        shopInfo['specialTime'] = eleShop.specialtime
    elif mtShop:
        shopInfo['isEnable'] = mtShop.isenable
        shopInfo['targetExposure'] = mtShop.targetExposure
        shopInfo['budget'] = mtShop.budget
        shopInfo['adTime'] = mtShop.adTime
        shopInfo['specialTime'] = mtShop.specialtime
    return shopInfo

def getShopsInfowithShopInfo(eleShop , mtShop, shopType):
    '''
    获取店铺的基本信息
    :param shipId:
    :param shopType:
    :return:
    '''
    shopInfo = {}
    if eleShop:
        shopInfo['isEnable'] = eleShop.isenable
        shopInfo['targetExposure'] = eleShop.targetExposure
        shopInfo['budget'] = eleShop.budget
        shopInfo['adTime'] = eleShop.adTime
        shopInfo['specialTime'] = eleShop.specialtime
    elif mtShop:
        shopInfo['isEnable'] = mtShop.isenable
        shopInfo['targetExposure'] = mtShop.targetExposure
        shopInfo['budget'] = mtShop.budget
        shopInfo['adTime'] = mtShop.adTime
        shopInfo['specialTime'] = mtShop.specialtime
    return shopInfo


def updateShopInfo(account, shopType, **kwags):
    '''
    更新店铺信息
    :param account: 账号
    :param shopType: 店铺种类
    :param kwags: 更新参数
    :return:
    '''
    account = account
    shopType = shopType
    shopid = kwags.get("shopid", None)
    shipTime = kwags.get("shipTime", "")
    adTime = kwags.get("adTime", "")
    percent = kwags.get("percent", "")
    shopStatus = kwags.get("shopStatus", None)
    cookies = kwags.get("cookies", "")
    budget = kwags.get("budget", None)
    isEnable = kwags.get("isEnable", None)
    isOnline = kwags.get("isOnline", None)
    deleted = kwags.get("deleted", None)
    targetExposure = kwags.get("targetExposure", None)
    isBind = kwags.get("isBind", None)
    specialTime = kwags.get("specialTime", "")
    userName = kwags.get("userName", "")
    guard = kwags.get("guard", None)
    try:
        session = Session()
        if shopType == 1:
            mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()
            if shopid:
                mt.shopid = shopid

            if shipTime:
                mt.shipTime = shipTime
            if adTime:
                mt.adTime = adTime
            if percent:
                mt.percent = percent
            if shopStatus != None:
                mt.shopStatus = shopStatus
            if cookies:
                mt.cookies = cookies
            if budget:
                mt.budget = budget
            if isEnable != None:
                mt.isenable = isEnable
            if isOnline != None:
                mt.isonline = isOnline
            if deleted != None:
                mt.deleted = deleted
            if targetExposure:
                mt.targetExposure = targetExposure
            if isBind != None:
                mt.isbind = isBind
            if specialTime:
                mt.specialtime = specialTime
            if userName:
                mt.userName = userName
            if guard != None:
                mt.guard = guard

            mt.updatetime = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
        elif shopType == 2:
            ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()
            if shopid:
                ele.shopid = shopid

            if shipTime:
                ele.shipTime = shipTime
            if adTime:
                ele.adTime = adTime
            if percent:
                ele.percent = percent
            if shopStatus != None:
                ele.shopStatus = shopStatus
            if cookies:
                ele.cookies = cookies
            if budget:
                ele.budget = budget
            if isEnable != None:
                ele.isenable = isEnable
            if isOnline != None:
                ele.isonline = isOnline
            if deleted != None:
                ele.deleted = deleted
            if targetExposure:
                ele.targetExposure = targetExposure
            if isBind != None:
                ele.isbind = isBind
            if specialTime:
                ele.specialtime = specialTime
            if userName:
                ele.userName = userName
            if guard != None:
                ele.guard = guard
            ele.updatetime = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
        session.commit()
        session.close()
        return True
    except:
        return False


def testGetAllShops():
    '''
       获取该账号的所有店铺
       :param bid: 加密的密码
       :return:
       '''
    try:
        result = None
        session = Session()
        # userName=session.query(Admin.userName).filter(Admin.bid==bid).scalar()
        # if not userName:
        #     session.close()
        #     result=1000
        # else:
        eleShopList = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == '170418850').all()
        mtShopList = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == '3808654').all()
        session.close()
        eleShop = []
        mtShop = []
        for shop in eleShopList:
            eleShop.append({"name": "小厨私房菜", "shopType": shop.shopType, "shopId": shop.shopId})
        for shop in mtShopList:
            mtShop.append({"name": "小厨私房菜", "shopType": shop.shopType, "shopId": shop.shopId})
        result = {"eleShop": eleShop, "mtShop": mtShop}
        return result
    except:
        return False
    pass


def getAllBiddingShops(deleted=0):
    '''
    获取所有需要进行推广的店铺
    :param deleted:
    :return:
    '''
    session = Session()
    ele = session.query(ShopEleInfo).filter(ShopEleInfo.deleted == deleted).all()
    mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.deleted == deleted).all()
    session.close()
    shop_dict = {}
    shop_ele = []
    shop_mt = []
    for s in ele:
        ad = ''
        if s.adTime:
            try:
                sadTime = eval(s.adTime)
                for i in sadTime:
                    ad += i.get('s') + "-" + i.get('e') + ','
                ad = ad[0:-1]
            except:
                ad = s.adTime

        shop = dict(
            id=s.eleId,
            isEnable=s.isenable,
            shoptype=2,
            name=s.eleName,
            account=s.account,
            shipTime=s.shipTime,
            createTime = s.createtime,
            deleteTime=s.result if s.result is not None else "",
            adTime=ad,
            shopId=s.eleId,
            status=1,
            upd=0,
        )
        shop_ele.append(shop)
    for s in mt:
        ad = ''
        if s.adTime:
            try:
                sadTime = eval(s.adTime)
                for i in sadTime:
                    ad += i.get('s') + "-" + i.get('e') + ','
                ad = ad[0:-1]
            except:
                ad = s.adTime
        shop = dict(
            id=s.mtId,
            isEnable=s.isenable,
            shoptype=1,
            name=s.mtName,
            account=s.account,
            shipTime=s.shipTime,
            createTime=s.createtime,
            deleteTime=s.result if s.result is not None else "",
            adTime=ad,
            shopId=s.mtId,
            status=1,
            upd=0,
        )
        shop_mt.append(shop)
    shop_dict = {"ele": shop_ele, "mt": shop_mt}
    return shop_dict


def changeDeletedVal(shopId, shopType, deleted):
    session = Session()
    try:
        if shopType == 1:
            mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).scalar()
            mt.deleted = deleted
            if deleted == 1:
                mt.result = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        elif shopType == 2:
            ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).scalar()
            ele.deleted = deleted
            if deleted == 1:
                ele.result = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        session.commit()
        session.close()
        return True
    except:
        return False
def changeDeletedShopStatus(account, shopType, deleted):
    session = Session()
    try:
        if shopType == 1:
            mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).scalar()
            mt.deleted = deleted
            if deleted == 1:
                mt.result = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        elif shopType == 2:
            ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).scalar()
            ele.deleted = deleted
            if deleted == 1:
                ele.result = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        session.commit()
        session.close()
        return True
    except:
        return False


def getShopCookieByShopId(shopId, type):
    session = Session()
    if type == 2:
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).scalar()
        if ele and ele.cookies != '':
            return ele.cookies
        else:
            return False
    elif type == 1:
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).scalar()

        if mt and mt.cookies != '':
            return mt.cookies
        else:
            return False


def setShopInfo(shopId, shopType, busy, budget):
    try:
        session = Session()
        shop = None
        if shopType == 2:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).scalar()
        elif shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).scalar()
        shop.budget = budget
        # shop.busyTime = str(busy)
        # 修改specialTime
        specialTime = shop.specialtime
        if specialTime == '[]' or specialTime == None:
            pass
        else:
            specialTime = eval(specialTime)
            busyp1 = 1
            busyp2 = 1
            busyp3 = 1
            busyp4 = 1
            busyp5 = 1
            idlep1 = 1
            idlep2 = 1
            idlep3 = 1
            idlep4 = 1
            idlep5 = 1
            rate = 5
            for t in specialTime:
                if t.get('type') == 1:
                    busyp1 = t.get('p1')
                    busyp2 = t.get('p2')
                    busyp3 = t.get('p3')
                    busyp4 = t.get('p4')
                    busyp5 = t.get('p5')
                    rate = t.get('rate')
                elif t.get('type') == 0:
                    idlep1 = t.get('p1')
                    idlep2 = t.get('p2')
                    idlep3 = t.get('p3')
                    idlep4 = t.get('p4')
                    idlep5 = t.get('p5')
                    rate = t.get('rate')

        busyTime = busy.get('busyTime')

        busyTime = eval(busyTime)
        idleTime = []
        busyTime.sort()
        for i in range(len(busyTime)):
            res = busyTime[i].split("-")
            if res[0] != "00:00" and i == 0:
                idleTime.append("00:00-" + res[0])
            if i + 1 == len(busyTime) and res[1] != '24:00':
                idleTime.append(res[1] + "-24:00")
            else:
                if i + 1 < len(busyTime) and res[1] != busyTime[i + 1].split("-")[0]:
                    idleTime.append(res[1] + "-" + busyTime[i + 1].split("-")[0])

        newSpecialTime = []
        for bztime in busyTime:
            s = bztime.split("-")[0]
            e = bztime.split("-")[1]
            newSpecialTime.append(
                {'s': s, 'e': e, 'p1': busyp1, 'p2': busyp2, 'p3': busyp3, 'p4': busyp4, 'rate': rate, 'p5': busyp5,
                 'type': 1, 'p6': busy.get('busyMinPrice'), 'p7': busy.get('busyMaxPrice')})
        for idltime in idleTime:
            s = idltime.split("-")[0]
            e = idltime.split("-")[1]
            newSpecialTime.append(
                {'s': s, 'e': e, 'p1': idlep1, 'p2': idlep2, 'p3': idlep3, 'p4': idlep4, 'rate': rate, 'p5': idlep5,
                 'type': 0, 'p6': busy.get('idleMinPrice'), 'p7': busy.get('idleMaxPrice')})
        shop.specialtime = str(newSpecialTime)
        shop.updatetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        session.commit()
        session.close()
        return True
    except:
        logger.warning("手机端设置接口:")
        logger.warning(traceback.format_exc())
        return False


def getShopInfoforSet(shopId, shopType):
    session = Session()
    shop = None
    if shopType == 2:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).scalar()
    elif shopType == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).scalar()
    specialTime = shop.specialtime
    budget = shop.budget
    if specialTime:
        busyTime = eval(specialTime)
        busyMax = 1.4
        busyMin = 0.6
        idleMax = 1.2
        idleMin = 0.4
        busy = []
        idle = []
        for t in busyTime:
            if t.get('type') == 1:
                try:
                    busyMax = float(t.get('p7'))
                    busyMin = float(t.get('p6'))
                except:
                    busyMax = 1.4
                    busyMin = 0.6
                busy.append(t.get('s') + "-" + t.get('e'))
            elif t.get('type') == 0:
                try:
                    idleMax = float(t.get('p7'))
                    idleMin = float(t.get('p6'))
                except:
                    idleMax = 1.2
                    idleMin = 0.4
                idle.append(t.get('s') + '-' + t.get('e'))
        return {"busyMaxPrice": busyMax, "busyMinPrice": busyMin, "idleMaxPrice": idleMax, "idleMinPrice": idleMin,
                "busyTime": busy, "idleTime": idle, "budget": float(budget)}
    else:
        return None


def changeHistoryVal(shopId, shopType, date, historymode):
    try:

        session = Session()
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()

        historyCurbid = shop.historyCurbid
        if historyCurbid:
            historyCurbid = eval(historyCurbid)
        historyCurbid["status"] = historymode
        shop.historyCurbid = str(historyCurbid)
        shop.updatetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        session.commit()
        session.close()
        return True
    except:
        return False


def getCurrentCurbid(curbidlst):
    if curbidlst:
        now = datetime.datetime.now().strftime("%H:%M")
        hour = now.split(":")[0]
        minute = now.split(":")[1]
        index = int(hour) * 2
        if int(minute) > 30:
            index += 2
        else:
            index += 1
        bid = curbidlst[index - 1]
        bid = round(bid, 1) * 100
        return bid
    else:
        return 40


def getShopInfoforNewSet(shopId, shopType):
    session = Session()
    shop = None
    id = None

    if shopType == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).scalar()
        id = shop.mtId
        cookies = shop.cookies
    elif shopType == 2:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).scalar()
        id = shop.eleId
        cookies = shop.cookies

    today = datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")
    now = (datetime.datetime.now() + datetime.timedelta(minutes=-5)).strftime("%Y-%m-%d %H:%M:%S")
    log = session.query(ShopBidding).filter(ShopBidding.shopid == id, ShopBidding.biddingTime > today).order_by(
        ShopBidding.id.desc()).first()

    balance = None
    realBudget = None
    if log and log.biddingTime > now:
        balance = log.blance
        realBudget = log.todayBudget
    else:
        if shopType == 1:
            mt = MTSpider(cookies)
            balance = mt.getBlance() / 100
            details = mt.getDetail(None)
            realBudget = details.get("budget") / 100
        elif shopType == 2:
            ele = ELESpider(cookies)
            balance = ele.getBlance()
            adPrice = ele.getAdPrice()
            realBudget = adPrice.get("budget", 0)

    specialtime = shop.specialtime
    idleLowPrice = ''
    idleHighPrice = ''
    busyLowPrice = ''
    busyHighPrice = ''
    if not specialtime or specialtime == '[]':
        busyLowPrice = ''
        busyMidPrice = ''
        busyHighPrice = ''
        busyLimitPrice = ''
        busyLowTimes = ''
        busyHighTimes = ''
        busyMaxTimes = ''
        idleLowPrice = ''
        idleMidPrice = ''
        idleHighPrice = ''
        idleLimitPrice = ''
        idleLowTimes = ''
        idleHighTimes = ''
        idleMaxTimes = ''
    else:
        specialtime = eval(specialtime)
        for st in specialtime:
            if st.get('type') == 1:
                if st.get('p6') == 'undefined':
                    busyLowPrice = ''
                else:
                    busyLowPrice = st.get('p6')
                if st.get('p7') == 'undefined':
                    busyHighPrice = ''
                else:
                    busyHighPrice = st.get('p7')

                busyMidPrice = st.get('p4')
                busyLimitPrice = st.get('p5')
                busyLowTimes = st.get('p2')
                busyHighTimes = st.get('p1')
                busyMaxTimes = st.get('p3')
            else:
                if st.get('p6') == 'undefined':
                    idleLowPrice = ''
                else:
                    idleLowPrice = st.get('p6')

                if st.get('p7') == 'undefined':
                    busyHighPrice = ''
                else:
                    idleHighPrice = st.get('p7')

                idleMidPrice = st.get('p4')
                idleLimitPrice = st.get('p5')
                idleLowTimes = st.get('p2')
                idleHighTimes = st.get('p1')
                idleMaxTimes = st.get('p3')

    busyPara = {"busyLowPrice": busyLowPrice, "busyMidPrice": busyMidPrice, "busyHighPrice": busyHighPrice,
                "busyLimitPrice": busyLimitPrice,
                "busyLowTimes": busyLowTimes, "busyHighTimes": busyHighTimes, "busyMaxTimes": busyMaxTimes}
    idlePara = {"idleLowPrice": idleLowPrice, "idleMidPrice": idleMidPrice, "idleHighPrice": idleHighPrice,
                "idleLimitPrice": idleLimitPrice,
                "idleLowTimes": idleLowTimes, "idleHighTimes": idleHighTimes, "idleMaxTimes": idleMaxTimes}
    budget = shop.budget
    targetExposure = shop.targetExposure
    deleted = shop.deleted
    isenable = shop.isenable
    guard = shop.guard
    return {"balance": balance, "budget": budget, "realBudget": realBudget, "targetExposure": targetExposure,
            "deleted": deleted, "isenable": isenable,
            "guard": guard, "busyPara": busyPara, "idlePara": idlePara}


def new_set_shop(data):
    shopId = data.get("shopId")
    shopType = int(data.get("shopType"))
    budget = data.get("budget")
    deleted = data.get("deleted")
    isenable = data.get("isenable")
    guard = data.get("guard")
    busyLowPrice = data.get("busyLowPrice")
    busyMidPrice = data.get("busyMidPrice")
    busyHighPrice = data.get("busyHighPrice")
    busyLimitPrice = data.get("busyLimitPrice")
    busyLowTimes = data.get("busyLowTimes")
    busyHighTimes = data.get("busyHighTimes")
    busyMaxTimes = data.get("busyMaxTimes")
    idleLowPrice = data.get("idleLowPrice")
    idleMidPrice = data.get("idleMidPrice")
    idleHighPrice = data.get("idleHighPrice")
    idleLimitPrice = data.get("idleLimitPrice")
    idleLowTimes = data.get("idleLowTimes")
    idleHighTimes = data.get("idleHighTimes")
    idleMaxTimes = data.get("idleMaxTimes")
    rate = data.get("rate")
    busy = data.get("busy")
    idle = data.get("idle")

    session = Session()
    if shopType == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.shopId == shopId).first()
    else:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.shopId == shopId).first()

    if budget is not None and budget != '':
        shop.budget = budget

    if deleted is not None and deleted != '':
        shop.deleted = int(deleted)

    if isenable is not None and isenable != '':
        shop.isenable = int(isenable)

    if guard is not None and guard != '':
        shop.guard = int(guard)

    specialtime = []
    if busy is not None and busy != '':
        busy = eval(busy)
        for bztime in busy:
            start = bztime.split("-")[0]
            end = bztime.split("-")[1]
            res = {'s': start, 'e': end, 'type': 1, 'rate': rate, 'p1': busyHighTimes, 'p2': busyLowTimes,
                   'p3': busyMaxTimes, 'p4': busyMidPrice, 'p5': busyLimitPrice, 'p6': busyLowPrice,
                   'p7': busyHighPrice}
            specialtime.append(res)

    if idle is not None and idle != '':
        idle = eval(idle)
        for bztime in idle:
            start = bztime.split("-")[0]
            end = bztime.split("-")[1]
            res = {'s': start, 'e': end, 'type': 0, 'rate': rate, 'p1': idleHighTimes, 'p2': idleLowTimes,
                   'p3': idleMaxTimes, 'p4': idleMidPrice, 'p5': idleLimitPrice, 'p6': idleLowPrice,
                   'p7': idleHighPrice}
            specialtime.append(res)
    specialtime = str(specialtime)
    print(specialtime)


def changeShopBudget(shopId, shopType, budget):
    try:
        cookies = getShopCookieByShopId(shopId, shopType)
        if shopType == 1:
            mt = MTSpider(cookies)
            mt.setBudget(budget)
        else:
            ele = ELESpider(cookies)
            ele.setBudget(budget)

        return True
    except:
        return False


def getmode1(shopId, shopType):
    session = Session()
    shop = None
    budget = ''
    balance = ''
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
            if not shop:
                return False
            cookies = shop.cookies
            mt = MTSpider(cookies)
            details = mt.getDetail(None)
            budget = int(details.get("budget") / 100)
            balance = mt.getBlance() / 100
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
            if not shop:
                return False
            cookies = shop.cookies
            ele = ELESpider(cookies)
            adPrice = ele.getAdPrice()
            budget = adPrice.get("budget", 0)
            balance = ele.getBlance()
        return {"budget": budget, "balance": balance, "orderRate": '', "enterRate": '', "serviceDay": '',
                'serviceStart': '', 'serviceEnd': ''}

    except:
        return False


def getmode2(shopId, shopType):
    # session = Session()
    # shop = None
    # try:
    #     if shopType == 1:
    #         shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    #     else:
    #         shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
    #     if not shop:
    #         return False
    #     cookies = shop.cookies
    #     budget = shop.budget
    #     targetExposure = shop.targetExposure
    #
    #     # 查询并处理adTime
    #     adTimeList = []
    #     adTime = shop.adTime
    #     if adTime:
    #         adTime = eval(adTime)
    #         for at in adTime:
    #             adTimeList.append(at.get('s') + "-" + at.get('e'))
    #
    #     # 查询并处理specialtime
    #     busyTimeList = []
    #     specialtime = shop.specialtime
    #     busyMaxPrice = ''
    #     busyMinPrice = ''
    #     idleMaxPrice = ''
    #     idleMinPrice = ''
    #     ct = datetime.datetime.strftime(datetime.datetime.now(), "%H:%M")
    #     if not specialtime or specialtime == '[]':
    #         pass
    #     else:
    #         specialtime = eval(specialtime)
    #         for st in specialtime:
    #             if st.get("s") == '00:00':
    #                 st["s"] = adTimeList[0].split("-")[0]
    #             if st.get("e") == '24:00':
    #                 st["e"] = adTimeList[-1].split("-")[-1]
    #             busyTimeList.append({
    #                 "time": st.get("s")+"-"+st.get("e"),
    #                 "maxPrice": st.get("p6"),
    #                 "minPrice": st.get("p7"),
    #                 "type": st.get("type")})
    #
    #     shipTimeList = []
    #     shipTime = shop.shipTime
    #     if shipTime:
    #         sps = shipTime.split(",")
    #         for sp in sps:
    #             shipTimeList.append(sp)
    #     status = shop.isenable
    #
    #     return {"budget": budget, "targetExposure": targetExposure, "busyMaxPrice": busyMaxPrice,
    #             "busyMinPrice": busyMinPrice, "idleMaxPrice": idleMaxPrice,
    #             "idleMinPrice": idleMinPrice, "adTimeList": adTimeList, "shipTimeList": shipTimeList,
    #             "busyTimeList": busyTimeList, "status": status}
    # except:
    #     return False
    session = Session()
    shop = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
        if not shop:
            return False
        cookies = shop.cookies
        budget = shop.budget
        targetExposure = shop.targetExposure

        # 查询并处理adTime
        adTimeList = []
        adTime = shop.adTime
        if adTime:
            adTime = eval(adTime)
            for at in adTime:
                adTimeList.append(at.get('s') + "-" + at.get('e'))

        # 查询并处理specialtime
        busyTimeList = []
        timeList = []
        specialtime = shop.specialtime
        busyMaxPrice = ''
        busyMinPrice = ''
        idleMaxPrice = ''
        idleMinPrice = ''
        ct = datetime.datetime.strftime(datetime.datetime.now(), "%H:%M")
        if not specialtime or specialtime == '[]':
            pass
        else:
            specialtime = eval(specialtime)
            for st in specialtime:
                if st.get('type') == 1:
                    busyTimeList.append(st.get('s') + "-" + st.get('e'))
                    busyMinPrice = st.get('p6')
                    busyMaxPrice = st.get('p7')
                else:
                    idleMinPrice = st.get('p6')
                    idleMaxPrice = st.get('p7')
                if st.get("s") == '00:00':
                    st["s"] = adTimeList[0].split("-")[0]
                if st.get("e") == '24:00':
                    st["e"] = adTimeList[-1].split("-")[-1]
                timeList.append({
                    "time": st.get("s")+"-"+st.get("e"),
                    "minPrice": st.get("p6"),
                    "maxPrice": st.get("p7"),
                    "type": st.get("type")})

        shipTimeList = []
        shipTime = shop.shipTime
        if shipTime:
            sps = shipTime.split(",")
            for sp in sps:
                shipTimeList.append(sp)
        status = shop.isenable

        return {"budget": budget, "targetExposure": targetExposure, "busyMaxPrice": busyMaxPrice,
                "busyMinPrice": busyMinPrice, "idleMaxPrice": idleMaxPrice,
                "idleMinPrice": idleMinPrice, "adTimeList": adTimeList, "shipTimeList": shipTimeList,
                "busyTimeList": busyTimeList, "status": status, "timeList": timeList}
    except:
        return False


def setmode2(data):
    shopId = data.get("shopId")
    shopType = data.get("shopType")
    targetExposure = data.get("targetExposure")
    budget = data.get("budget")
    adTime = data.get("adTime")
    busyTime = data.get("busyTime")
    busyMaxPrice = 0 if data.get("busyMaxPrice") == '' else data.get("busyMaxPrice")
    busyMinPrice = 0 if data.get("busyMinPrice") == '' else data.get("busyMaxPrice")
    idleMaxPrice = 0 if data.get("idleMaxPrice") == '' else data.get("busyMaxPrice")
    idleMinPrice = 0 if data.get("idleMinPrice") == '' else data.get("busyMaxPrice")
    immediate = data.get("immediate")

    session = Session()
    busy = ''
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
            account = shop.account
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
            account = shop.account
        busy = shop.specialtime
        specialtime = []
        busyMidPrice = ''
        busyLimitPrice = ''
        busyLowTimes = ''
        busyHighTimes = ''
        busyMaxTimes = ''
        rate = ''
        idleMidPrice = ''
        idleLimitPrice = ''
        idleLowTimes = ''
        idleHighTimes = ''
        idleMaxTimes = ''
        if busy is not None and busy != '':
            busy = eval(busy)
            for bztime in busy:
                if bztime.get("type") == 1:
                    busyMidPrice = bztime.get('p4')
                    busyLimitPrice = bztime.get('p5')
                    busyLowTimes = bztime.get('p2')
                    busyHighTimes = bztime.get('p1')
                    busyMaxTimes = bztime.get('p3')
                    rate = bztime.get('rate')
                else:
                    idleMidPrice = bztime.get('p4')
                    idleLimitPrice = bztime.get('p5')
                    idleLowTimes = bztime.get('p2')
                    idleHighTimes = bztime.get('p1')
                    idleMaxTimes = bztime.get('p3')
                    rate = bztime.get('rate')
        else:
            busyLowTimes = '0.9'
            busyHighTimes = '0.9'
            busyMaxTimes = '0.9'
            busyMidPrice = float(busyMinPrice) + 0.2
            busyMidPrice = str(busyMidPrice)
            busyLimitPrice = busyMaxPrice
            idleLowTimes = '0.9'
            idleHighTimes = '0.9'
            idleMaxTimes = '0.9'
            idleMidPrice = float(idleMaxPrice) - 0.2
            idleMidPrice = str(idleMidPrice)
            idleLimitPrice = idleMaxPrice
            rate = ''
        busyTime = eval(busyTime)
        idleTime = []
        busyTime = sorted(busyTime, key=lambda x : x['time'])

        # for i in range(len(busyTime)):
        #     res = busyTime[i].split("-")
        #     if res[0] != "00:00" and i == 0:
        #         idleTime.append("00:00-" + res[0])
        #     if i + 1 == len(busyTime) and res[1] != '24:00':
        #         idleTime.append(res[1] + "-24:00")
        #     else:
        #         if i + 1 < len(busyTime) and res[1] != busyTime[i + 1].split("-")[0]:
        #             idleTime.append(res[1] + "-" + busyTime[i + 1].split("-")[0])
        k = 0
        busyTimeLen = len(busyTime)
        for bztime in busyTime:
            time = bztime.get("time")
            maxPrice = bztime.get("maxPrice")
            minPrice = bztime.get("minPrice")
            s = time.split("-")[0]
            e = time.split("-")[1]
            if k == 0:
                s = '00:00'
            if k == busyTimeLen - 1:
                e = '24:00'
            specialtime.append(
                {'s': s, 'e': e, 'p1': busyHighTimes, 'p2': busyLowTimes, 'p3': busyMaxTimes, 'p4': busyMidPrice,
                 'rate': rate, 'p5': busyLimitPrice,
                 'type': bztime.get("type"), 'p6': minPrice, 'p7': maxPrice})
            k = k + 1
        adTimeList = []
        adTime = eval(adTime)
        for at in adTime:
            adTimeList.append({'s': at.split("-")[0], 'e': at.split("-")[1], 'p': '1'})
        if immediate == 1:
            shop.adTime = str(adTimeList)
            shop.specialtime = str(specialtime)
            if budget is not None and budget != '' and budget != 'NaN':
                shop.budget = int(budget)

        else:
            day = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
            plan = {"budget": int(budget), "adTime": str(adTimeList),
                    "busyMaxPrice": busyMaxPrice, "busyMinPrice": busyMinPrice, "idleMaxPrice": idleMaxPrice,
                    "idleMinPrice": idleMinPrice, "day": day}
            shop.plan = str(plan)
        session.commit()
        session.close()
        return {"account": account, "adTime": str(adTimeList), "targetExposure": targetExposure}
    except:
        session.close()
        return False

def setMobileMode2SetCopy(shopId, shopType, timeList, budget):
    """
    手机端设置specialtime字段
    :param shopId:
    :param shopType:
    :param timeList:
    :param budget:
    :return:
    """
    session = Session()
    busy = ''
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
            account = shop.account
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
            account = shop.account
        busy = shop.specialtime
        specialtime = []
        busyMidPrice = ''
        busyLimitPrice = ''
        busyLowTimes = ''
        busyHighTimes = ''
        busyMaxTimes = ''
        rate = ''
        idleMidPrice = ''
        idleLimitPrice = ''
        idleLowTimes = ''
        idleHighTimes = ''
        idleMaxTimes = ''
        if busy is not None and busy != '':
            busy = eval(busy)
            for bztime in busy:
                if bztime.get("type") == 1:
                    busyMidPrice = bztime.get('p4')
                    busyLimitPrice = bztime.get('p5')
                    busyLowTimes = bztime.get('p2')
                    busyHighTimes = bztime.get('p1')
                    busyMaxTimes = bztime.get('p3')
                    rate = bztime.get('rate')
                else:
                    idleMidPrice = bztime.get('p4')
                    idleLimitPrice = bztime.get('p5')
                    idleLowTimes = bztime.get('p2')
                    idleHighTimes = bztime.get('p1')
                    idleMaxTimes = bztime.get('p3')
                    rate = bztime.get('rate')
        else:
            busyLowTimes = '0.9'
            busyHighTimes = '0.9'
            busyMaxTimes = '0.9'
            busyMidPrice = '0.4'
            busyMidPrice = str(busyMidPrice)
            busyLimitPrice = '0.4'
            idleLowTimes = '0.9'
            idleHighTimes = '0.9'
            idleMaxTimes = '0.9'
            idleMidPrice = '0.4'
            idleMidPrice = str(idleMidPrice)
            idleLimitPrice = '0.4'
            rate = ''
        busyTime = eval(timeList)
        idleTime = []
        busyTime = sorted(busyTime, key=lambda x: x['time'])

        # for i in range(len(busyTime)):
        #     res = busyTime[i].split("-")
        #     if res[0] != "00:00" and i == 0:
        #         idleTime.append("00:00-" + res[0])
        #     if i + 1 == len(busyTime) and res[1] != '24:00':
        #         idleTime.append(res[1] + "-24:00")
        #     else:
        #         if i + 1 < len(busyTime) and res[1] != busyTime[i + 1].split("-")[0]:
        #             idleTime.append(res[1] + "-" + busyTime[i + 1].split("-")[0])
        k = 0
        busyTimeLen = len(busyTime)
        for bztime in busyTime:
            time = bztime.get("time")
            maxPrice = bztime.get("maxPrice")
            minPrice = bztime.get("minPrice")
            s = time.split("-")[0]
            e = time.split("-")[1]
            if k == 0:
                s = '00:00'
            if k == busyTimeLen - 1:
                e = '24:00'
            specialtime.append(
                {'s': s, 'e': e, 'p1': busyHighTimes, 'p2': busyLowTimes, 'p3': busyMaxTimes, 'p4': busyMidPrice,
                 'rate': rate, 'p5': busyLimitPrice,
                 'type': bztime.get("type"), 'p6': minPrice, 'p7': maxPrice})
            k = k + 1
        adTimeList = []
        shop.specialtime = str(specialtime)
        if budget is not None and budget != '':
            shop.budget = int(budget)
        session.commit()
        return {"account": account}
    except:
        session.rollback()
        return False
    finally:
        session.close()

def getIdleMaxPrice(shopId, shopType, specialtime):
    shop = None
    failure = 0
    msg = ''
    session = Session()
    if shopType == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        mt = MTSpider(shop.cookies)
        try:
            res = mt.getTrendList("1", "1")
            avgSevenShopInfo = mt.getAvgSevenShopInfo()
            daysAvgPrice = avgSevenShopInfo.get("avgPrice")

            if not res:
                failure = 1
                msg += "闲忙时下单转化率获取失败;"
                return {"failure": failure, "msg": msg}
            else:
                flowChartsInfoList = res.get("flowChartsInfoList")
                orderRateList = []
                for flowChartsInfo in flowChartsInfoList:
                    orderRateList.append(flowChartsInfo.get("orderRate"))
                if sum(orderRateList) == 0:
                    failure = 1
                    msg += "下单转化率获取失败;店铺昨日可能未营业;"
                    return {"failure": failure, "msg": msg}
                busyTime = []
                idleOrderRateList = []
                if specialtime:
                    specialtime = eval(specialtime)
                    for st in specialtime:
                        if st.get("type") == 1:
                            s = st.get("s")
                            e = st.get("e")
                            if int(e.split(":")[1]) == 0:
                                l = int(e.split(":")[0]) - int(s.split(":")[0]) - 1
                            else:
                                l = int(e.split(":")[0]) - int(s.split(":")[0])
                            if orderRateList[int(s.split(":")[0])] != 0:
                                busyTime.append(orderRateList[int(s.split(":")[0])])
                            for i in range(l):
                                if orderRateList[int(s.split(":")[0]) + i] != 0:
                                    busyTime.append(orderRateList[int(s.split(":")[0]) + i])
                        else:
                            temp = []
                            s = st.get("s")
                            e = st.get("e")
                            if int(e.split(":")[1]) == 0:
                                l = int(e.split(":")[0]) - int(s.split(":")[0]) - 1
                            else:
                                l = int(e.split(":")[0]) - int(s.split(":")[0])
                            if orderRateList[int(s.split(":")[0])] != 0:
                                temp.append(orderRateList[int(s.split(":")[0])])
                            for i in range(1,l + 1):
                                if orderRateList[int(s.split(":")[0]) + i] != 0:
                                    temp.append(orderRateList[int(s.split(":")[0]) + i])
                            if len(temp) == 0:
                                idleOrderRateList.append(0)
                            else:
                                idleOrderRateList.append(round(sum(temp) / len(temp), 4))
                avgBusyOrderRate = round(sum(busyTime) / len(busyTime), 4)
                return {"failure":failure, "msg":msg, "avgBusyOrderRate" : avgBusyOrderRate,"idleOrderRateList":idleOrderRateList ,"daysAvgPrice":daysAvgPrice}
        except:
            logger.info(traceback.format_exc())
            logger.info("美团：闲时订单下单率获取失败shopId:{}".format(shopId))
            return False
    else:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
        cookies = shop.cookies
        try:
            ele = ELESpider(cookies)

            daysExposure = ele.get7DaysExposure()
            daysAvgPrice = daysExposure.get("averageCost")

            day = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
            result = ele.getYesOverViewData(day, day)
            if result:
                itemValue = result.get("flowData").get("buyerConvRateDist").get("itemValue")
                itemList = sorted(itemValue.items(), key=lambda x: x[0])
            else:
                failure = 1
                msg += "闲忙时下单转化率获取失败;"
                return {"failure": failure, "msg": msg}

            orderRateList = []
            for item in itemList:
                orderRateList.append(item[1])
            if sum(orderRateList) == 0:
                failure = 1
                msg += "下单转化率获取失败;店铺昨日可能未营业;"
                return {"failure": failure, "msg": msg}
            busyTime = []
            idleOrderRateList = []
            if specialtime:
                specialtime = eval(specialtime)
                for st in specialtime:
                    if st.get("type") == 1:
                        s = st.get("s")
                        e = st.get("e")
                        if int(e.split(":")[1]) == 0:
                            l = int(e.split(":")[0]) - int(s.split(":")[0]) - 1
                        else:
                            l = int(e.split(":")[0]) - int(s.split(":")[0])
                        if orderRateList[int(s.split(":")[0])] != 0:
                            busyTime.append(orderRateList[int(s.split(":")[0])])
                        for i in range(l):
                            if orderRateList[int(s.split(":")[0]) + i] != 0:
                                busyTime.append(orderRateList[int(s.split(":")[0]) + i])
                    else:
                        temp = []
                        s = st.get("s")
                        e = st.get("e")
                        if int(e.split(":")[1]) == 0:
                            l = int(e.split(":")[0]) - int(s.split(":")[0]) - 1
                        else:
                            l = int(e.split(":")[0]) - int(s.split(":")[0])
                        if orderRateList[int(s.split(":")[0])] != 0:
                            temp.append(orderRateList[int(s.split(":")[0])])
                        for i in range(1, l + 1):
                            if orderRateList[int(s.split(":")[0]) + i] != 0:
                                temp.append(orderRateList[int(s.split(":")[0]) + i])
                        if len(temp) == 0:
                            idleOrderRateList.append(0)
                        else:
                            idleOrderRateList.append(round(sum(temp) / len(temp), 4))
            avgBusyOrderRate = round(sum(busyTime) / len(busyTime), 4)

            return {"failure": failure, "msg": msg, "avgBusyOrderRate": avgBusyOrderRate,
                    "idleOrderRateList": idleOrderRateList, "daysAvgPrice":daysAvgPrice}
        except:
            logger.info(traceback.format_exc())
            logger.info("饿了么：闲时订单下单率获取失败shopId:{}".format(shopId))
            return False



def getmode3(shopId, shopType):
    session = Session()
    shop = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()

        session.close()
        if not shop:
            return False

        historyCurbid = shop.historyCurbid
        status = 0
        curbidList = []
        if historyCurbid:
            historyCurbid = eval(historyCurbid)
            curbid = historyCurbid.get('curbid')
            status = historyCurbid.get("status")
            curbidList = eval(curbid)

        return {"status": status, "curbidList": curbidList}
    except:
        return False


def setmode3(shopId, shopType, curbidList):
    session = Session()
    shop = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()

        historyCurbid = {"status": 0, "curbid": curbidList}
        historyCurbid = str(historyCurbid)
        shop.historyCurbid = historyCurbid

        # 如果打开定时定价，需要确保竞价开，监控关
        # if status == 1:
        #     shop.isenable = 1
        #     shop.guard = 0

        session.commit()
        session.close()
        return True
    except:
        session.close()
        return False


def getmode4(shopId, shopType):
    session = Session()
    shop = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()

        status = shop.guard
        session.close()
        return {"status": status}
    except:
        return False


def setmode4(shopId, shopType, status):
    session = Session()
    shop = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()

        # shop.guard = status
        # if status == 1:
        #     #shop.isenable = 1
        #     historyCurbid = shop.historyCurbid
        #     if historyCurbid:
        #         historyCurbid = eval(historyCurbid)
        #         historyCurbid['status'] = 0
        #         historyCurbid = str(historyCurbid)
        #         shop.historyCurbid = historyCurbid
        #
        # session.commit()
        session.close()
        return True
    except:
        return False


def getUserName(bid):
    session = Session()
    user = session.query(Admin).filter(Admin.bid == bid).first()
    session.close()
    return user.userName


def getProxyIp():
    try:
        session = Session2()
        ips = session.query(IpPool).filter(IpPool.valid == 1).order_by(IpPool.shopnum).all()
        session.close()

        if not ips:
            return None
        else:
            ip = ips[0].ip
            return ip
    except:
        logger.info(traceback.format_exc())
        return None


def saveShop(cookies, shopName, account, bid = None):
    try:
        oldShop = False
        id = ''
        shopType = 0
        userName = 'super001'
        if not bid:
            userName = 'super001'
        else:
            userName = getUserName(bid)
        createtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        cookies = cookies.replace(' ', '')
        if 'wmPoiId' in cookies:
            shopType = 1
            cookiesLst = cookies.split(";")
            for cookie in cookiesLst:
                if 'wmPoiId' in cookie:
                    id = cookie.split("=")[1]
                    id = int(id)
                    break
        elif 'ele' in cookies:
            shopType = 2
            cookiesLst = cookies.split(";")
            for cookie in cookiesLst:
                if 'eleshopid' in cookie:
                    id = cookie.split("=")[1]
                    id = int(id)
                    break
        session = Session()
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()
        ctime = str(time.time())
        shopId = myMd5(ctime, str(id))

        ip = getProxyIp()

        if shop:
            oldShop = True
            if shopType == 1:
                shop.mtId = id
                shop.cookies = cookies
                shop.updatetime = createtime
            elif shopType == 2:
                shop.eleId = id
                shop.cookies = cookies
                shop.updatetime = createtime
        else:
            if shopType == 1:
                session.add(
                    ShopMeituanInfo(
                        mtId=id,
                        cookies=cookies,
                        salt=ctime,
                        shopId=shopId,
                        mtName=shopName,
                        account=account,
                        shopType=1,
                        isenable=1,
                        userName=userName,
                        createtime=createtime,
                        updatetime=createtime,
                        deleted=0,
                        guard = 1,
                        ip = ip ,
                    )
                )

            elif shopType == 2:
                session.add(
                    ShopEleInfo(
                        eleId=id,
                        cookies=cookies,
                        salt=ctime,
                        shopId=shopId,
                        eleName=shopName,
                        account=account,
                        shopType=2,
                        isenable=1,
                        userName=userName,
                        createtime=createtime,
                        updatetime=createtime,
                        deleted=0,
                        guard=1,
                    )
                )

        session.commit()
        session.close()
        return {"shopId": id, "shopType": shopType , "oldShop": oldShop}
    except:
        return False


def getShopidInfo(shop_data):
    shopList = []
    shopId = None
    shopType = None
    shopName = None

    try:
        shop_data = json.loads(shop_data)
    except:
        shop_data = shop_data
    for data in shop_data:
        mt = None
        ele = None
        shopType = data.get("type")
        account = data.get("account")
        shopIcon = data.get("icon",None)
        sId = data.get("shopId","")
        deadTime = data.get("deadTime","")
        agency = data.get("agency","")
        cost = data.get("cost")
        if shopIcon is None or shopIcon == '':
            shopIcon = None
        else:
            shopIcon = shopIcon.split(".webp@80w")[0]
        session = Session()
        if shopType == 1:
            mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account,ShopMeituanInfo.deleted == 0).first()
        elif shopType == 2:
            ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == account, ShopEleInfo.deleted == 0).first()
        session.close()

        if not mt and not ele:
            shopList.append(None)
        elif mt:
            shopType = 1
            shopId = mt.shopId
            shopName = mt.mtName
            if shopIcon is None:
                shopList.append({"shopId": shopId, "shopType": shopType, "shopName": shopName,"sId":sId,"deadTime":deadTime, "agency": agency, "account": account, "cost": cost})
            else:
                shopList.append({"shopId": shopId, "shopType": shopType, "shopName": shopName, "shopIcon":shopIcon,"sId":sId,"deadTime":deadTime, "agency": agency, "account": account, "cost": cost})
        elif ele:
            shopType = 2
            shopId = ele.shopId
            shopName = ele.eleName
            shopList.append({"shopId": shopId, "shopType": shopType, "shopName": shopName, "shopIcon":shopIcon,"sId":sId,"deadTime":deadTime, "agency": agency, "account": account, "cost": cost})
    return shopList


def setNewShopBaseInfo(shopId, shopType, account, shopCookies, suggestBudget, suggestTargetExposure, suggestMaxPrice,
                       suggestMinPrice, shipTime):
    shop = None
    shopinfo = None
    createtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    try:
        session = Session()
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
        if shop:
            shop.budget = suggestBudget
            shop.targetExposure = suggestTargetExposure
            result = formatAdtAndSpt(shipTime)
            adTime = result.get('date').get('adTimeResult')
            for at in adTime:
                if at.get('e') == '00:00':
                    at['e'] = '23:59'
            adTime = str(adTime)
            shop.adTime = adTime
            session.commit()
            session.close()
            get4DaysOrder(shopCookies, shopType, account)
        return True
    except:
        logger.warning(traceback.format_exc())
        return False


def setBusyandIdle(shopId, shopType, suggestMaxPrice, suggestMinPrice):
    session = Session()
    shop = None

    if shopType == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    else:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
    if shop:
        # if shop.percent:
        #     percent = eval(shop.percent)
        #     rate = 0.045
        #     s = sum(percent)
        #     busyTimeList = []
        #     idleTimeList = []
        #     busy = []
        #     idle = []
        #     for i in range(1, 49):
        #         if percent[i - 1] / s >= rate:
        #             busy.append(i)
        #         else:
        #             idle.append(i)
        #     ##
        #     bstart = busy[0]
        #     count = 0
        #     index = 0
        #     for i in range(len(busy) - 1):
        #         count += 1
        #         if busy[i] + 1 == busy[i + 1]:
        #             pass
        #         else:
        #             if count - index == 1:
        #                 busyTimeList.append({'s': getTimeByIndex(bstart - 1), 'e': getTimeByIndex(bstart)})
        #                 index = count
        #                 bstart = busy[i + 1]
        #             else:
        #                 bend = busy[i]
        #                 busyTimeList.append({'s': getTimeByIndex(bstart - 1), 'e': getTimeByIndex(bend)})
        #                 bstart = busy[i + 1]
        #
        #     bend = busy[len(busy) - 1]
        #     busyTimeList.append({'s': getTimeByIndex(bstart - 1), 'e': getTimeByIndex(bend)})
        #
        #     bstart = idle[0]
        #     count = 0
        #     index = 0
        #     for i in range(len(idle) - 1):
        #         count += 1
        #         if idle[i] + 1 == idle[i + 1]:
        #             pass
        #         else:
        #             if count - index == 1:
        #                 idleTimeList.append({'s': getTimeByIndex(bstart - 1), 'e': getTimeByIndex(bstart)})
        #                 index = count
        #                 bstart = idle[i + 1]
        #             else:
        #                 bend = idle[i]
        #                 idleTimeList.append({'s': getTimeByIndex(bstart - 1), 'e': getTimeByIndex(bend)})
        #                 bstart = idle[i + 1]
        #
        #     bend = idle[len(idle) - 1]
        #     idleTimeList.append({'s': getTimeByIndex(bstart - 1), 'e': getTimeByIndex(bend)})
        #     for bt in busyTimeList:
        #         bt['type'] = 1
        #         bt['rate'] = '4.5'
        #         bt['p1'] = '0.9'
        #         bt['p2'] = '0.9'
        #         bt['p3'] = '0.9'
        #         bt['p4'] = str(round(float(suggestMaxPrice) - 0.1, 1))
        #         bt['p6'] = str(suggestMinPrice)
        #         bt['p7'] = str(suggestMaxPrice)
        #         bt['p5'] = str(suggestMaxPrice)
        #     for bt in idleTimeList:
        #         bt['type'] = 2
        #         bt['rate'] = '4.5'
        #         bt['p1'] = '0.9'
        #         bt['p2'] = '0.9'
        #         bt['p3'] = '0.9'
        #         bt['p4'] = str(round(float(suggestMaxPrice) - 0.1, 1))
        #         bt['p6'] = str(suggestMinPrice)
        #         bt['p7'] = str(suggestMaxPrice)
        #         bt['p5'] = str(suggestMaxPrice)
        #         busyTimeList.append(bt)
        #     print(busyTimeList)
            shop.specialtime = None
            session.commit()
            session.close()
            return True


def getTimeByIndex(i):
    h = ""
    if i % 2 == 0:
        h = math.floor(i / 2)
        if h < 10:
            h = "0" + str(h) + ":00"
        else:
            h = str(h) + '' + ":00"
    else:
        h = math.floor(i / 2)
        if h < 10:
            h = "0" + str(h) + ":30"
        else:
            h = str(h) + '' + ":30"
    return h


def get4DaysOrder(cookies, shopType, account):
    orderDayNum = 4
    mins = 30
    orderDayNum = -1 * orderDayNum
    if shopType == 1:
        try:
            mt = MTSpider(cookies)
            daysNum = mt.get7daysOrder(orderDayNum)
            allOrderLists = []
            percent = [0 for i in range(48)]
            ct = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:00")
            for dayNum in daysNum:
                if len(dayNum) != 0:
                    dayNum.sort()
                    timelst = []
                    for order in dayNum:
                        timelst.append(order.split(' ')[1])
                    dayperiod = {}
                    i = 0
                    j = 15
                    index = 0
                    a = 0
                    while i < 24:
                        while j <= 60:
                            if j == 60:
                                j = 0
                                break
                            else:
                                t = "%02d:%02d:00" % (i, j)
                                dayperiod[t] = 0
                                while index < len(timelst) and timelst[index] < t:
                                    dayperiod[t] = dayperiod[t] + 1
                                    index += 1
                                j += 15
                        i += 1
                    dayperiod["23:59:59"] = 0
                    for tl in timelst:
                        if tl > '23:45:00' and tl <= '23:59:59':
                            a += 1
                    dayperiod["23:59:59"] = a
                    orderList = []  # 目前orderlist是96个
                    for key, value in dayperiod.items():
                        orderList.append(value)
                    periodOrderList = []
                    index = 0
                    if mins == 30:
                        # 将俩个俩个相加，变成48个
                        while index <= 94:
                            periodOrderList.append(orderList[index] + orderList[index + 1])
                            index += 2
                    for i in range(48):
                        percent[i] += periodOrderList[i]
                    periodOrderList = str(periodOrderList)
                    allOrderLists.append(periodOrderList)
            ##将Percent存起来
            session = Session()
            shop = None
            if shopType == 1:
                shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).first()
            else:
                shop = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()
            shop.percent = str(percent)
            session.commit()
            session.close()
            for i in range(orderDayNum, 0):
                daytime = datetime.datetime.now() + datetime.timedelta(days=i)
                daytime = daytime.strftime("%Y-%m-%d")
                updYseOrderInfo(account, allOrderLists[i - orderDayNum], daytime, ct)
        except:
            print("获取订单失败")
    else:
        try:
            ele = ELESpider(cookies)
            percent = [0 for i in range(48)]
            for i in range(orderDayNum, 0):
                day = (datetime.datetime.now() + datetime.timedelta(days=i)).strftime("%Y-%m-%d")
                daystart = day + "T00:00:00"
                dayend = day + "T23:59:59"
                daysNum = ele.getAllOrder(daystart, dayend, 200)
                timelst = []
                # 所有下单时间存进列表
                if daysNum:
                    for dayNum in daysNum:
                        # 2019-10-01T21:22:09,返回的时间是这样的，只取21:22:09
                        timelst.append(dayNum.get("activeTime").split('T')[1])
                    timelst.sort()
                    dayperiod = {}
                    i = 0
                    j = 15
                    a = 0
                    index = 0
                    while i < 24:
                        while j <= 60:
                            if j == 60:
                                j = 0
                                break
                            else:
                                t = "%02d:%02d:00" % (i, j)
                                dayperiod[t] = 0
                                while index < len(timelst) and timelst[index] < t:
                                    dayperiod[t] = dayperiod[t] + 1
                                    index += 1
                                j += 15
                        i += 1
                    dayperiod["23:59:59"] = 0
                    for tl in timelst:
                        if tl > '23:45:00' and tl <= '23:59:59':
                            a += 1
                    dayperiod["23:59:59"] = a
                    orderList = []  # 目前orderlist是96个
                    for key, value in dayperiod.items():
                        orderList.append(value)
                    periodOrderList = []
                    index = 0
                    if mins == 30:
                        # 将俩个俩个相加，变成48个
                        while index <= 94:
                            periodOrderList.append(orderList[index] + orderList[index + 1])
                            index += 2
                    for i in range(48):
                        percent[i] += periodOrderList[i]
                    periodOrderList = str(periodOrderList)
                    ct = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:00")
                    updYseOrderInfo(account, periodOrderList, day, ct)
            session = Session()
            shop = None
            if shopType == 1:
                shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).first()
            else:
                shop = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()
            shop.percent = str(percent)
            session.commit()
            session.close()
        except:
            print("获取订单失败")


def formatAdtAndSpt(shipTime):
    '''
    获取正确格式的推广时间和营业时间数组
    :param shipTime:
    :return: [],[]
    '''
    try:
        shipTimeResult = []
        adTimeResult = []
        shipTimes = shipTime.split(",")
        if shipTimes[-1] == '':
            shipTimes = shipTimes[0:-1]
        '''将后面时间点小于前面时间点的时间段分成两个时间段，
                并且如果前一个时间段的最后时间与后一个时间段的第一个时间相等，进行合并'''
        for everyShipTime in shipTimes:
            shopT, shipT = divideShipTime(everyShipTime)
            adTimeResult += shopT
            shipTimeResult += shipT
        if adTimeResult == {} or shipTimeResult == []:
            return resultJson("", 2000, "格式化时间错误", 1)
        return resultJson({"adTimeResult": adTimeResult, "shipTimeResult": shipTimeResult}, 6000, "格式化时间正确", 0)
    except:
        return resultJson("", 2000, "格式化时间错误", 1)


def divideShipTime(everyShipTime):
    '''
    跨越24：00的时间段分成两个时间段
    :param everyShipTime:
    :return:[]
    '''
    shipTimeList = []
    shopTimeList = []
    timePoint = everyShipTime.split("-")
    endTimeStr = ''
    if timePoint[1] == '00:00' or timePoint[1] == '24:00':
        endTimeStr = '23:59'
    else:
        endTimeStr = timePoint[1]
    baseTime = datetime.datetime.now().strftime("%Y-%m-%d")
    if timePoint[0] > endTimeStr:
        startOne = baseTime + " " + "00:00" + ":00"
        startTwo = baseTime + " " + timePoint[0] + ":00"
        endOne = baseTime + " " + timePoint[1] + ":00"
        # endTwo=baseTime+" "+"23:50"+":00"
        startOne = formateTimeM(startOne, 10)
        startTwo = formateTimeM(startTwo, 10)
        endOne = formateTimeM(endOne, -10)
        shipTimeList.append(timePoint[0] + '-' + timePoint[1])
        if endOne != "00:00":
            shopTimeList.append({"s": startOne, "e": endOne, "p": '1'})
        # shipTimeList.append(timePoint[0]+"-23:59")
        shopTimeList.append({"s": startTwo, "e": "23:50", "p": '1'})
    else:
        shipTimeList.append(timePoint[0] + "-" + timePoint[1])
        if endTimeStr == "23:59":
            endOne = "23:50"
        else:
            endOne = baseTime + " " + timePoint[1] + ":00"
            endOne = formateTimeM(endOne, -10)
        startOne = baseTime + " " + timePoint[0] + ":00"
        startOne = formateTimeM(startOne, 10)
        if startOne != "00:00":
            shopTimeList.append({"s": startOne, "e": endOne, "p": '1'})
    return shopTimeList, shipTimeList


def formateTimeM(timeStr, offset):
    '''

    :param timeStr:
    :param offset:
    :return:
    '''
    timeMid = (datetime.datetime.strptime(timeStr, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(minutes=offset))
    timeM = timeMid.strftime("%M")
    timeH = timeMid.strftime("%H")
    timeMToInt = int(int(timeM) / 10) * 10
    if timeMToInt == 0:
        timeMToInt = "00"
    endOne = timeH + ":" + str(timeMToInt)
    return endOne


def resultJson(date, code, message, error=0):
    '''
    将数据Json标准化返回
    :param date:
    :param code:
    :param message:
    :return:
    '''
    return {"date": date, "code": code, "message": message, "error": error}


def getdata7(shopId, shopType):
    session = Session()
    shop = None
    try:
        shopInfo = [{}, {}, {}, {}, {}, {}, {}]
        for i in range(7):
            shopInfo[i] = {"budget": '',
                           "targetExposure": '',
                           "busyMaxPrice": '',
                           "busyMinPrice": '',
                           "idleMaxPrice": '',
                           "idleMinPrice": '',
                           "maxPrice": '',
                           "minPrice": '',
                           "historyCurbid": {'status': 0, 'curbid': [{"start": "", "end": "", "price": ""}]}
                           }

        shops = session.query(DaysDatum).filter(DaysDatum.shopId == shopId, DaysDatum.shopType == shopType).order_by(
            DaysDatum.day).all()
        for shop in shops:
            dayIndex = int(shop.day) - 1
            historyCurbid = shop.historyCurbid
            if historyCurbid:
                historyCurbid = eval(historyCurbid)
                curbidList = historyCurbid.get('curbid')
                curbidList = eval(curbidList)
                for curbid in curbidList:
                    start = curbid.get("time").split("-")[0]
                    end = curbid.get("time").split("-")[1]
                    curbid["start"] = start
                    curbid["end"] = end
                historyCurbid['curbid'] = curbidList

            budget = shop.budget
            targetExposure = shop.targetExposure
            busyMaxPrice = shop.busyMaxPrice
            busyMinPrice = shop.busyMinPrice
            idleMaxPrice = shop.idleMaxPrice
            idleMinPrice = shop.idleMinPrice
            maxPrice = shop.maxPrice
            minPrice = shop.minPrice
            shopInfo[dayIndex] = {"budget": budget, "targetExposure": targetExposure, "busyMaxPrice": busyMaxPrice,
                                  "busyMinPrice": busyMinPrice, "idleMaxPrice": idleMaxPrice,
                                  "idleMinPrice": idleMinPrice, "maxPrice": maxPrice, "minPrice": minPrice,
                                  "historyCurbid": historyCurbid}
        return shopInfo
    except:
        return False


def setdata7(shopId, shopType, daysData):
    session = Session()
    shop = None
    daysData = json.loads(daysData)
    shops = session.query(DaysDatum).filter(DaysDatum.shopId == shopId, DaysDatum.shopType == shopType).order_by(
        DaysDatum.day).all()
    if shops:
        for i in range(len(shops)):
            budget = daysData[i].get('budget') if daysData[i].get("budget") != '' else None
            targetExposure = daysData[i].get("targetExposure") if daysData[i].get("targetExposure") != '' else None
            busyMaxPrice = daysData[i].get("busyMaxPrice") if daysData[i].get("busyMaxPrice") != '' else None
            busyMinPrice = daysData[i].get("busyMinPrice") if daysData[i].get("busyMinPrice") != '' else None
            idleMaxPrice = daysData[i].get("idleMaxPrice") if daysData[i].get("idleMaxPrice") != '' else None
            idleMinPrice = daysData[i].get("idleMinPrice") if daysData[i].get("idleMinPrice") != '' else None
            historyCurbid = daysData[i].get("historyCurbid")
            maxPrice = daysData[i].get("maxPrice") if daysData[i].get("maxPrice") != '' else None
            minPrice = daysData[i].get("minPrice") if daysData[i].get("minPrice") != '' else None
            status = daysData[i].get("historyCurbid").get("status")
            if status == True:
                status = 1
            elif status == False:
                status = 0
            historyCurbid["status"] = status
            curbid = historyCurbid.get('curbid')
            curbidList = []
            for item in curbid:
                if item["start"].strip() != '' and item["end"].strip() != '':
                    item['time'] = item["start"] + "-" + item["end"]
                    item.pop("start")
                    item.pop("end")
                    curbidList.append(item)
            curbid = str(curbidList)
            historyCurbid["curbid"] = curbid
            historyCurbid = str(historyCurbid)
            shops[i].budget = budget
            shops[i].targetExposure = targetExposure
            shops[i].busyMaxPrice = busyMaxPrice
            shops[i].busyMinPrice = busyMinPrice
            shops[i].idleMaxPrice = idleMaxPrice
            shops[i].idleMinPrice = idleMinPrice
            shops[i].historyCurbid = historyCurbid
            shops[i].maxPrice = maxPrice
            shops[i].minPrice = minPrice

        session.commit()
        session.close()
    else:
        for i in range(7):
            budget = daysData[i].get('budget') if daysData[i].get("budget") != '' else None
            targetExposure = daysData[i].get("targetExposure") if daysData[i].get("targetExposure") != '' else None
            busyMaxPrice = daysData[i].get("busyMaxPrice") if daysData[i].get("busyMaxPrice") != '' else None
            busyMinPrice = daysData[i].get("busyMinPrice") if daysData[i].get("busyMinPrice") != '' else None
            idleMaxPrice = daysData[i].get("idleMaxPrice") if daysData[i].get("idleMaxPrice") != '' else None
            idleMinPrice = daysData[i].get("idleMinPrice") if daysData[i].get("idleMinPrice") != '' else None
            historyCurbid = daysData[i].get("historyCurbid")
            maxPrice = daysData[i].get("maxPrice") if daysData[i].get("maxPrice") != '' else None
            minPrice = daysData[i].get("minPrice") if daysData[i].get("minPrice") != '' else None
            status = daysData[i].get("historyCurbid").get("status")
            if status == True:
                status = 1
            elif status == False:
                status = 0
            curbid = historyCurbid.get('curbid')
            curbidList = []
            for item in curbid:
                if item["start"].strip() != '' and item["end"].strip() != '':
                    item['time'] = item["start"] + "-" + item["end"]
                    item.pop("start")
                    item.pop("end")
                    curbidList.append(item)
            curbid = str(curbidList)
            historyCurbid["curbid"] = curbid
            historyCurbid = str(historyCurbid)
            session.add(
                DaysDatum(
                    shopId=shopId,
                    shopType=shopType,
                    day=i + 1,
                    budget=budget,
                    targetExposure=targetExposure,
                    busyMaxPrice=busyMaxPrice,
                    busyMinPrice=busyMinPrice,
                    idleMaxPrice=idleMaxPrice,
                    idleMinPrice=idleMinPrice,
                    historyCurbid=historyCurbid,
                    maxPrice=maxPrice,
                    minPrice=minPrice,
                ))

        session.commit()
        session.close()

    return True


def getHourTargetExposureEle(account, ct, dt_ad, type):
    '''

    :param account:
    :param ct:
    :param dt_ad:
    :param type:
    :return:
    '''
    try:
        session = Session()
        shopBiddingTarget = session.query(ShopBiddingTarget).filter(ShopBiddingTarget.account == account,
                                                                    ShopBiddingTarget.type == type,
                                                                    or_(ShopBiddingTarget.exposureTime == ct,
                                                                        ShopBiddingTarget.exposureTime == dt_ad)).first()
        session.close()
        if not shopBiddingTarget:
            target = 0
            budget = 0
        else:
            target = shopBiddingTarget.exposureNum
            budget = shopBiddingTarget.budget
        return {"target": target, "budget": budget}
    except:
        print(traceback.format_exc())
        logger.warning(traceback.format_exc())


def getCurbidCount(shopId, shopType, date):
    session = Session()
    shop = None
    specialTime = None
    account = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).scalar()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).scalar()
        account = shop.account
        specialTime = shop.specialtime
        if not specialTime:
            return False
        yesOrder = session.query(YesOrderInfo).filter(YesOrderInfo.account == account, YesOrderInfo.day == date).scalar()
        if yesOrder:
            if not yesOrder.priceCount:
                result = getBusyandIdleCurbidCount(specialTime, date, shopId)
                res = str(result)
                ct = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                yesOrder.priceCount = res
                yesOrder.updatetime = ct
                session.commit()
                session.close()
                return result
            else:
                session.close()
                return eval(yesOrder.priceCount)
        else:
            result = getBusyandIdleCurbidCount(specialTime, date, shopId)
            res = str(result)
            ct = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            session.add(YesOrderInfo(
                account=account,
                updatetime=ct,
                day=date,
                priceCount=res,
            ))
            session.commit()
            session.close()
            return result
    except:
        return False


def getBusyandIdleCurbidCount(specialTime, date, shopId):
    session = Session()
    specialTime = eval(specialTime)
    busyTimeList = []
    for st in specialTime:
        if st.get('type') == 1:
            busyTimeList.append(st)
    busyPriceCount = {}
    idlePriceCount = {}
    date = datetime.datetime.strptime(date, "%Y-%m-%d")
    nowTime = datetime.datetime.now().strftime("%Y-%m-%d")
    daysNum = (datetime.datetime.strptime(nowTime, "%Y-%m-%d") - date).days
    daysNum = -1 * daysNum

    for i in range(daysNum - 7, daysNum):
        start = (datetime.datetime.now() + datetime.timedelta(days = i)).strftime("%Y-%m-%d") + " 14:00:00"
        end = (datetime.datetime.now() + datetime.timedelta(days = i + 1)).strftime("%Y-%m-%d") + " 00:00:00"
        daysLog = session.query(ShopBidding.biddingTime, ShopBidding.exposureNum, ShopBidding.basePrice) \
            .filter(
            ShopBidding.shopid == shopId,
            ShopBidding.biddingTime >= start,
            ShopBidding.biddingTime < end
        ).all()
        for i in range(0, len(daysLog) - 1):
            if judgeIsInBusyTime(busyTimeList, daysLog[i][0]):
                if datetime.datetime.strptime(daysLog[i][0], "%Y-%m-%d %H:%M:%S") + datetime.timedelta(
                        minutes=2) == datetime.datetime.strptime(daysLog[i + 1][0], "%Y-%m-%d %H:%M:%S"):
                    if daysLog[i + 1][1] - daysLog[i][1] >= 0:
                        if not float(daysLog[i][2]) in busyPriceCount.keys():
                            busyPriceCount[float(daysLog[i][2])] = float(daysLog[i + 1][1] - daysLog[i][1])
                        else:
                            busyPriceCount[float(daysLog[i][2])] = busyPriceCount[float(daysLog[i][2])] + float(
                                daysLog[i + 1][1] - daysLog[i][1])

            else:
                if datetime.datetime.strptime(daysLog[i][0], "%Y-%m-%d %H:%M:%S") + datetime.timedelta(
                        minutes=2) == datetime.datetime.strptime(daysLog[i + 1][0], "%Y-%m-%d %H:%M:%S"):
                    if daysLog[i + 1][1] - daysLog[i][1] >= 0:
                        if not daysLog[i][2] in idlePriceCount.keys():
                            idlePriceCount[float(daysLog[i][2])] = float(daysLog[i + 1][1] - daysLog[i][1])
                        else:
                            idlePriceCount[float(daysLog[i][2])] = idlePriceCount[float(daysLog[i][2])] + float(
                                daysLog[i + 1][1] - daysLog[i][1])

    busyPriceCountTuple = sorted(busyPriceCount.items(), key=lambda x: x[0])
    idlePriceCountTuple = sorted(idlePriceCount.items(), key=lambda x: x[0])

    busyPriceCount = {}
    idlePriceCount = {}
    for t in busyPriceCountTuple:
        if not int(t[1]) == 0:
            busyPriceCount[t[0]] = int(t[1])
    for t in idlePriceCountTuple:
        if not int(t[1]) == 0:
            idlePriceCount[t[0]] = int(t[1])

    res = {"busyPriceCount": busyPriceCount, "idlePriceCount": idlePriceCount}
    return res


def judgeIsInBusyTime(busyTimeList, nowTime):
    nowTime = nowTime[11:16]
    for bt in busyTimeList:
        if nowTime >= bt.get('s') and nowTime <= bt.get('e'):
            return True
        else:
            return False


def getStatusMode(shopId, shopType):
    session = Session()
    shop = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).scalar()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).scalar()
        ##status2:竞价开关状态
        status2 = shop.isenable
        historyCurbid = shop.historyCurbid
        ##定时定价开关状态
        status3 = 0
        if historyCurbid:
            historyCurbid = eval(historyCurbid)
            status3 = historyCurbid.get("status")
        ##监控开关状态
        status4 = shop.guard

        if status3 == 1:
            status2 = 0
        if status4 == 1:
            status2 = 0

        if status3 == 1 and status4 == 1:
            status4 = 0
        return {"status2": status2, "status3": status3, "status4": status4}
    except:
        logger.info("获取3个状态异常")
        return False
def newGetShopOrder(sid):
    today = datetime.datetime.now().strftime("%Y-%m-%d")
    firstDay = (datetime.datetime.now() + datetime.timedelta(days=-8)).strftime("%Y-%m-%d")
    session = Session()
    account, type = getAccountById(sid)
    order_list = []
    day_list = []
    num_list = []
    for i in range(-7, 0):
        day = (datetime.datetime.now() + datetime.timedelta(days=i)).strftime("%Y-%m-%d")
        orderList = session.query(YesOrderInfo).filter(YesOrderInfo.account == account,
                                                       YesOrderInfo.day == day).first()
        day_list.append(day)
        if orderList:
            if orderList.InfoList:
                lst = eval(orderList.InfoList)
                res = [0 for i in range(24)]
                for i in range(1,25):
                    res[i-1] = lst[i*2 - 1] + lst[i*2 - 2]
                num_list.append(sum(res))
                order_list.append({"infoList": res, "null": 0, "num": sum(res),"day":day})
            else:
                num_list.append(0)
                order_list.append({"infoList": [0 for i in range(24)], "null": 1, "num": 0,"day":day})
        else:
            num_list.append(0)
            order_list.append({"infoList": [0 for i in range(24)], "null": 1,"day":day,"num":0})
    return {"order_lst":order_list,"day_list":day_list,"num_list":num_list}
def saveSettings(data):

    account = data.get("account")
    shopType = data.get("shopType")
    targetExposure = data.get("targetExposure")
    budget = data.get("budget")
    adTime = data.get("adTime")
    controlRate = data.get("controlRate")
    baseRate = data.get("baseRate")
    idleMinPrice = data.get("idleMinPrice")
    busyMaxPrice = data.get("busyMaxPrice")
    busyMinPrice = data.get("busyMinPrice")
    nextExposureRate = data.get("nextExposureRate")
    idleExposureRate = data.get("idleExposureRate")
    isenable = data.get("isenable")
    guard = data.get("guard")
    busyTimeLock = data.get("busyTimeLock")
    historyMode = data.get("historyMode")
    lock = data.get("lock")
    percent = data.get("percent")
    busyInfoList = data.get("busyInfoList")
    idleInfoList = data.get("idleInfoList")
    idleOrderRateList = data.get("idleOrderRateList")
    idleMaxPriceList = data.get("idleMaxPriceList")
    daysAvgPrice = data.get("daysAvgPrice","")
    busyOrderRate = data.get("busyOrderRate","")
    try:
        session = Session()
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()

        shop.targetExposure = targetExposure
        shop.budget = budget
        shop.isenable = isenable
        shop.guard = guard
        shop.busyTimeLock = busyTimeLock
        shop.adTime = adTime
        #nextExposureRate明日的曝光比
        shop.exposureRate = str({"controlRate":controlRate,"baseRate":baseRate,"nextExposureRate":nextExposureRate})
        #闲时曝光比
        shop.shopTimeEnd = idleExposureRate
        #推广时间锁定
        shop.isremake = lock

        specialtime = []
        busyInfoList = eval(busyInfoList)
        for index, busyInfo in list(enumerate(busyInfoList)):
            specialtime.append({'s' : busyInfo.split("-")[0], 'e' : busyInfo.split("-")[1], 'type':1,'rate':percent,
                                'p1': '1','p2':'1','p3':'1','p4':1,'p5':1,'p6':busyMinPrice,'p7':busyMaxPrice})

        idleInfoList = eval(idleInfoList)
        idleMaxPriceList = eval(idleMaxPriceList)
        for index, idleInfo in list(enumerate(idleInfoList)):
            specialtime.append({'s': idleInfo.split("-")[0], 'e': idleInfo.split("-")[1], 'type': 1, 'rate': percent,
                                'p1': '1', 'p2': '1', 'p3': '1', 'p4': 1, 'p5': 1, 'p6': idleMinPrice, 'p7': idleMaxPriceList[index]})

        shop.specialtime = str(specialtime)
        shop.updatetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        if shop.historyCurbid:
            try:
                historyCurbid = eval(shop.historyCurbid)
                historyCurbid['status'] = historyMode
                shop.historyCurbid = str(historyCurbid)
            except:
                logger.info(traceback.format_exc())
        if busyOrderRate!= "" and daysAvgPrice != "" :
            shop.orderRate = str({"busyOrderRate":busyOrderRate,"daysAvgPrice":daysAvgPrice,"idleOrderRateList":idleOrderRateList})
        session.commit()
        return True
    except:
        return False
    finally:
        session.close()





def setStatusMode(shopId, shopType, status2, status3, status4):
    session = Session()
    shop = None
    # try:
    if shopType == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).scalar()
    else:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).scalar()
    if status3 == 1:
        status2 = 1
    if status4 == 1:
        status2 = 1
    shop.isenable = status2
    shop.guard = status4
    historyCurbid = shop.historyCurbid
    if historyCurbid:
        historyCurbid = eval(historyCurbid)
        historyCurbid['status'] = status3
        historyCurbid = str(historyCurbid)
        shop.historyCurbid = historyCurbid
    session.commit()
    session.close()
    return True
    # except:
    #     logger.info("设置3个状态异常")
    #     return False


def saveTomorrowPara(**kwargs):
    mtaccount = kwargs.get("mtaccount", '')
    eleaccount = kwargs.get("eleaccount", '')
    elebudget = kwargs.get("elebudget", 0)
    mtbudget = kwargs.get("mtbudget", 0)
    budget = 0
    if elebudget == 0:
        budget = mtbudget
    else:
        budget = elebudget
    mtadtime = kwargs.get("mtadtime", '')
    eleadtime = kwargs.get("eleadtime", '')
    mttargetExposure = kwargs.get("mttargetExposure", 0)
    eletargetExposure = kwargs.get("eletargetExposure", 0)
    percent = kwargs.get("percent")
    specialtime = kwargs.get("specialtime")

    busyMaxPrice = None
    busyMinPrice = None
    idleMaxPrice = None
    idleMinPrice = None

    specialtime = eval(specialtime)
    for st in specialtime:
        if st.get("type") == 1:
            busyMaxPrice = st.get("p7")
            busyMinPrice = st.get("p6")
        else:
            idleMaxPrice = st.get("p7")
            idleMinPrice = st.get("p6")
    day = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")

    session = Session()
    if mtaccount:
        mt = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == mtaccount).first()
        temp = {"budget": budget, "adTime": mtadtime, "targetExposure": mttargetExposure, "busyMaxPrice": busyMaxPrice,
                "busyMinPrice": busyMinPrice, "idleMaxPrice": idleMaxPrice, "idleMinPrice": idleMinPrice, "day": day}
        if mt.plan:
            plan = eval(mt.plan)
            plan.update(temp)
        else:
            plan = temp

        plan = str(plan)
        mt.plan = plan
        session.commit()
        session.close()

    if eleaccount:
        ele = session.query(ShopEleInfo).filter(ShopEleInfo.account == eleaccount).first()
        temp = {"budget": budget, "adTime": eleadtime, "targetExposure": eletargetExposure,
                "busyMaxPrice": busyMaxPrice,
                "busyMinPrice": busyMinPrice, "idleMaxPrice": idleMaxPrice, "idleMinPrice": idleMinPrice, "day": day}
        if ele.plan:
            plan = eval(plan)
            plan.update(temp)
        else:
            plan = temp
        plan = str(plan)
        ele.plan = plan
        session.commit()
        session.close()


def coverPlanPara(plan, account, type):
    budget = plan.get("budget")
    adTime = plan.get("adTime")
    targetExposure = plan.get("targetExposure")
    percent = plan.get("percent")
    busyMaxPrice = plan.get("busyMaxPrice")
    busyMinPrice = plan.get("busyMinPrice")
    idleMaxPrice = plan.get("idleMaxPrice")
    idleMinPrice = plan.get("idleMinPrice")
    session = Session()
    shop = None
    if type == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).first()
    else:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()

    shop.adTime = adTime
    shop.budget = budget
    shop.targetExposure = targetExposure

    specialtime = shop.specialtime
    specialtime = eval(specialtime)

    for st in specialtime:
        if st.get("type") == 1:
            st["p6"] = busyMinPrice
            st["p7"] = busyMaxPrice
        else:
            st["p6"] = idleMinPrice
            st["p7"] = idleMaxPrice

    shop.specialtime = str(specialtime)
    session.commit()
    session.close()


def isSpecialTime(specialtime, ct):
    """
    主要是判断当前时间在忙时还是闲时
    :param specialtime:
    :param ct:
    :return:
    """
    try:
        specialtime = eval(specialtime)
    except:
        specialtime = specialtime
    try:
        ct = datetime.datetime.strptime(ct, "%Y-%m-%d %H:%M:%S").strftime("%H:%M")
        type = 0
        for st in specialtime:
            if ct >= st.get('s') and ct < st.get('e'):
                type = st.get("type", 0)
                break
    except:
        type = 0
    return type


def mode2_set_for_mobile(shopId, shopType, busyMaxPrice, budget, status):
    session = Session()
    shop = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
        if not shop:
            return False
        shop.isenable = status
        shop.budget = budget

        busy = shop.specialtime
        if busy is not None and busy != '':
            busy = eval(busy)
            for bztime in busy:
                if bztime.get("type") == 1:
                    bztime['p7'] = str(busyMaxPrice)
        busy = str(busy)
        shop.specialtime = busy
        session.commit()
        session.close()
        return True
    except:
        return False


def judge_new_shop(shopId, shopType):
    session = Session()
    shop = None
    try:
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
        createTime = shop.createtime
        nowTime = (datetime.datetime.now() + datetime.timedelta(minutes=-30)).strftime("%Y-%m-%d %H:%M:%S")
        if createTime > nowTime:
            return True
        else:
            return False
    finally:
        session.close()


def getShopReportHeadInfo(shopId, shopType, day):
    session = Session()
    report = None
    try:
        '''实时获取余额'''
        balance = ''
        yesOrderNum = ''
        yesIncome = ''
        score = ''
        if shopType == 1:
            shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
            cookies = shop.cookies
            mt = MTSpider(cookies)
            balance = mt.getBlance() / 100
        else:
            shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
            cookies = shop.cookies
            ele = ELESpider(cookies)
            balance = ele.getBlance()

        yesterday = (datetime.datetime.strptime(day, "%Y-%m-%d") + datetime.timedelta(days = -1)).strftime("%Y-%m-%d")
        before_yesterday = (datetime.datetime.strptime(day, "%Y-%m-%d") + datetime.timedelta(days = -2)).strftime("%Y-%m-%d")
        before_week = (datetime.datetime.strptime(day, "%Y-%m-%d") + datetime.timedelta(days = -7)).strftime("%Y-%m-%d")


        yesterday_report = session.query(Report).filter(Report.shopId == shopId, Report.shopType == shopType, Report.date == yesterday).first()
        before_yesterday_report = session.query(Report).filter(Report.shopId == shopId, Report.shopType == shopType, Report.date == before_yesterday).first()
        before_week_report = session.query(Report).filter(Report.shopId == shopId, Report.shopType == shopType, Report.date == before_week).first()
        week_report = session.query(Report).filter(Report.shopId == shopId, Report.shopType == shopType).order_by(Report.date.desc())[0:7]
        '''获取报告头部三个数据'''
        if yesterday_report:
            yesOrderNum = yesterday_report.orderNum
            yesIncome = yesterday_report.settleAcc
            score = yesterday_report.score
        reportHeadInfo = {"yesOrderNum" : yesOrderNum, "yesIncome":yesIncome , "score" : score, "balance" : balance}



        '''数据看板模块'''
        effectiveOrders = ''
        exposureNum = ''
        income = ''
        cost = ''
        hisEffectiveOrders = ''
        hisExposureNum = ''
        hisIncome = ''
        hisCost = ''
        hisWeekEffectiveOrders = ''
        hisWeekExposureNum = ''
        hisWeekIncome = ''
        hisWeekCost = ''

        if yesterday_report:
            effectiveOrders = yesterday_report.effectiveOrders
            reportHeadInfo["yesOrderNum"] = effectiveOrders
            exposureNum = yesterday_report.exposureNum
            income = yesterday_report.settleAcc
            cost = yesterday_report.cost
        if before_yesterday_report:
            hisEffectiveOrders = before_yesterday_report.effectiveOrders
            hisExposureNum = before_yesterday_report.exposureNum
            hisIncome = before_yesterday_report.settleAcc
            hisCost = before_yesterday_report.cost

        if before_week_report:
            hisWeekEffectiveOrders = before_week_report.effectiveOrders
            hisWeekExposureNum = before_week_report.exposureNum
            hisWeekIncome = before_week_report.settleAcc
            hisWeekCost = before_week_report.cost

        if hisCost == -1:
            beforeYesLastLog = session.query(ShopBidding).filter(ShopBidding.shopid == shopId, ShopBidding.biddingTime > yesterday + " 00:00:00" , ShopBidding.biddingTime <= yesterday + " 23:58:00").order_by(ShopBidding.id.desc()).all()
            if beforeYesLastLog :
                hisCost = float(beforeYesLastLog[0].currentCost)

        if hisWeekCost == -1:
            weekLastLog = session.query(ShopBidding).filter(ShopBidding.shopid == shopId, ShopBidding.biddingTime > before_week + " 00:00:00" , ShopBidding.biddingTime <= before_week + " 23:58:00").order_by(ShopBidding.id.desc()).all()
            if weekLastLog:
                hisWeekCost = float(weekLastLog[0].currentCost)



        hisEffectiveOrdersRate = ''
        hisExposureNumRate = ''
        hisIncomeRate = ''
        hisCostRate = ''
        hisWeekEffectiveOrdersRate = ''
        hisWeekExposureNumRate = ''
        hisWeekIncomeRate = ''
        hisWeekCostRate = ''
        if yesterday_report and before_yesterday_report and hisEffectiveOrders != 0 and hisExposureNum != 0 and hisIncome != 0 :
            if effectiveOrders >= hisEffectiveOrders:
                hisEffectiveOrdersRate = int((effectiveOrders - hisEffectiveOrders) / hisEffectiveOrders * 100)
                hisEffectiveOrdersRate = "↑{}%".format(hisEffectiveOrdersRate)
            else:
                hisEffectiveOrdersRate = int((hisEffectiveOrders - effectiveOrders) / hisEffectiveOrders * 100)
                hisEffectiveOrdersRate = "↓{}%".format(hisEffectiveOrdersRate)
            if exposureNum >= hisExposureNum:
                hisExposureNumRate = int((exposureNum - hisExposureNum) / hisExposureNum * 100)
                hisExposureNumRate = "↑{}%".format(hisExposureNumRate)
            else:
                hisExposureNumRate = int((hisExposureNum - exposureNum) / hisExposureNum * 100)
                hisExposureNumRate = "↓{}%".format(hisExposureNumRate)
            if income >= hisIncome:
                hisIncomeRate = int((income - hisIncome) / hisIncome * 100)
                hisIncomeRate = "↑{}%".format(hisIncomeRate)
            else:
                hisIncomeRate = int((hisIncome - income) / hisIncome * 100)
                hisIncomeRate = "↓{}%".format(hisIncomeRate)

            if not cost == -1 and not hisCost == -1 and not hisCost == 0:
                # -1表示没有数据
                if cost >= hisCost:
                    hisCostRate = int((cost - hisCost) / hisCost * 100)
                    hisCostRate = "↑{}%".format(hisCostRate)
                else:
                    hisCostRate = int((hisCost - cost) / hisCost * 100)
                    hisCostRate = "↓{}%".format(hisCostRate)


        if yesterday_report and before_week_report and hisWeekEffectiveOrders != 0 and hisWeekExposureNum != 0 and hisWeekIncome != 0 :
            if effectiveOrders >= hisWeekEffectiveOrders:
                hisWeekEffectiveOrdersRate = int((effectiveOrders - hisWeekEffectiveOrders) / hisWeekEffectiveOrders * 100)
                hisWeekEffectiveOrdersRate = "↑{}%".format(hisWeekEffectiveOrdersRate)
            else:
                hisWeekEffectiveOrdersRate = int((hisWeekEffectiveOrders - effectiveOrders) / hisWeekEffectiveOrders * 100)
                hisWeekEffectiveOrdersRate = "↓{}%".format(hisWeekEffectiveOrdersRate)
            if exposureNum >= hisWeekExposureNum:
                hisWeekExposureNumRate = int((exposureNum - hisWeekExposureNum) / hisWeekExposureNum * 100)
                hisWeekExposureNumRate = "↑{}%".format(hisWeekExposureNumRate)
            else:
                hisWeekExposureNumRate = int((hisWeekExposureNum - exposureNum) / hisWeekExposureNum * 100)
                hisWeekExposureNumRate = "↓{}%".format(hisWeekExposureNumRate)
            if income >= hisWeekIncome:
                hisWeekIncomeRate = int((income - hisWeekIncome) / hisWeekIncome * 100)
                hisWeekIncomeRate = "↑{}%".format(hisWeekIncomeRate)
            else:
                hisWeekIncomeRate = int((hisWeekIncome - income) / hisWeekIncome * 100)
                hisWeekIncomeRate = "↓{}%".format(hisWeekIncomeRate)

            if not cost == -1 and not hisWeekCost == -1 and not hisWeekCost == 0:
                if cost >= hisWeekCost:
                    hisWeekCostRate = int((cost - hisWeekCost) / hisWeekCost * 100)
                    hisWeekCostRate = "↑{}%".format(hisWeekCostRate)
                else:
                    hisWeekCostRate = int((hisWeekCost - cost) / hisWeekCost * 100)
                    hisWeekCostRate = "↓{}%".format(hisWeekCostRate)

        dataBoard = dict(
            effectiveOrders = effectiveOrders,
            exposureNum = exposureNum,
            income = income,
            cost = cost if cost != -1 else '',
            hisEffectiveOrders = hisEffectiveOrders,
            hisExposureNum = hisExposureNum,
            hisIncome = hisIncome,
            hisCost = hisCost if hisCost != -1 else '',
            hisWeekEffectiveOrders = hisWeekEffectiveOrders,
            hisWeekExposureNum = hisWeekExposureNum,
            hisWeekIncome = hisWeekIncome,
            hisWeekcost = hisWeekCost if hisWeekCost != -1 else '',
            hisEffectiveOrdersRate = hisEffectiveOrdersRate,
            hisExposureNumRate =hisExposureNumRate,
            hisIncomeRate =  hisIncomeRate,
            hisCostRate = hisCostRate,
            hisWeekEffectiveOrdersRate = hisWeekEffectiveOrdersRate,
            hisWeekExposureNumRate = hisWeekExposureNumRate,
            hisWeekIncomeRate = hisWeekIncomeRate,
            hisWeekCostRate = hisWeekCostRate,
        )
        '''
            进店未下单，下单未完成
        '''
        clickNotOrderNum = ""
        orderNotFinishNum = ""
        beforeYesClickNotOrderNum = ""
        beforeYesOrderNotFinishNum = ""
        beforeWeekClickNotOrderNum = ""
        beforeWeekOrderNotFinishNum = ""

        beforeYesClickNotOrderRate = ""
        beforeWeekClickNotOrderRate = ""

        beforeYesOrderNotFinishRate = ""
        beforeWeekOrderNotFinishRate = ""

        if yesterday_report:
            clickNotOrderNum = yesterday_report.label1 if yesterday_report.label1 is not None else ""
            orderNotFinishNum = yesterday_report.label2 if yesterday_report.label2 is not None else ""
        if before_yesterday_report:
            beforeYesClickNotOrderNum = before_yesterday_report.label1 if before_yesterday_report.label1 is not None else ""
            beforeYesOrderNotFinishNum = before_yesterday_report.label2 if before_yesterday_report.label2 is not None else ""
        if before_week_report:
            beforeWeekClickNotOrderNum = before_week_report.label1 if before_week_report.label1 is not None else ""
            beforeWeekOrderNotFinishNum = before_week_report.label2 if before_week_report.label2 is not None else ""

        if clickNotOrderNum != -1 and clickNotOrderNum != "" and beforeYesClickNotOrderNum != "" and beforeYesClickNotOrderNum != -1:
            rate = (clickNotOrderNum - beforeYesClickNotOrderNum) / beforeYesClickNotOrderNum
            if rate > 0:
                beforeYesClickNotOrderRate = "↑{}%".format(int(rate*100))
            else:
                beforeYesClickNotOrderRate = "↓{}%".format(int(-1*rate*100))

        if orderNotFinishNum != -1 and orderNotFinishNum != "" and beforeYesOrderNotFinishNum != "" and beforeYesOrderNotFinishNum != -1:
            rate = (orderNotFinishNum - beforeYesOrderNotFinishNum) / beforeYesOrderNotFinishNum
            if rate > 0:
                beforeYesOrderNotFinishRate = "↑{}%".format(int(rate * 100))
            else:
                beforeYesOrderNotFinishRate = "↓{}%".format(int(-1 * rate * 100))

        if clickNotOrderNum != -1 and clickNotOrderNum != "" and beforeWeekClickNotOrderNum != "" and beforeWeekClickNotOrderNum != -1:
            rate = (clickNotOrderNum - beforeWeekClickNotOrderNum) / beforeWeekClickNotOrderNum
            if rate > 0:
                beforeWeekClickNotOrderRate = "↑{}%".format(int(rate * 100))
            else:
                beforeWeekClickNotOrderRate = "↓{}%".format(int(-1 * rate * 100))

        if orderNotFinishNum != -1 and orderNotFinishNum != "" and beforeWeekOrderNotFinishNum != "" and beforeWeekOrderNotFinishNum != -1:
            rate = (orderNotFinishNum - beforeWeekOrderNotFinishNum) / beforeWeekOrderNotFinishNum
            if rate > 0:
                beforeWeekOrderNotFinishRate = "↑{}%".format(int(rate * 100))
            else:
                beforeWeekOrderNotFinishRate = "↓{}%".format(int(-1 * rate * 100))

        customerLabelInfo = dict(
            clickNotOrderNum = clickNotOrderNum,
            beforeYesClickNotOrderNum = beforeYesClickNotOrderNum,
            beforeWeekClickNotOrderNum = beforeWeekClickNotOrderNum,
            beforeYesClickNotOrderRate = beforeYesClickNotOrderRate,
            beforeWeekClickNotOrderRate = beforeWeekClickNotOrderRate,
            orderNotFinishNum = orderNotFinishNum,
            beforeYesOrderNotFinishNum = beforeYesOrderNotFinishNum,
            beforeWeekOrderNotFinishNum = beforeWeekOrderNotFinishNum,
            beforeYesOrderNotFinishRate = beforeYesOrderNotFinishRate,
            beforeWeekOrderNotFinishRate = beforeWeekOrderNotFinishRate
        )

        '''
            新老客分析
        '''
        newSingle = ''
        oldSingle = ''
        newPercent = ''
        oldPercent = ''

        hisNewSingle = ''
        hisOldSingle = ''
        hisNewPercent = ''
        hisOldPercent = ''

        hisWeekNewSingle = ''
        hisWeekOldSingle = ''
        hisWeekNewPercent = ''
        hisWeekOldPercent = ''

        if yesterday_report:
            newSingle = yesterday_report.newSingle
            oldSingle = yesterday_report.oldSingle
            newPercent = yesterday_report.newPercent
            oldPercent = yesterday_report.oldPercent
        if before_yesterday_report:
            hisNewSingle = before_yesterday_report.newSingle
            hisOldSingle = before_yesterday_report.oldSingle
            hisNewPercent = before_yesterday_report.newPercent
            hisOldPercent = before_yesterday_report.oldPercent
        if before_week_report:
            hisWeekNewSingle = before_week_report.newSingle
            hisWeekOldSingle = before_week_report.oldSingle
            hisWeekNewPercent = before_week_report.newPercent
            hisWeekOldPercent = before_week_report.oldPercent
        hisNewSingleRate = ''
        hisOldSingleRate = ''
        hisWeekNewSingleRate = ''
        hisWeekOldSingleRate = ''

        hisRateRate = ''
        hisWeekRateRate = ''
        if yesterday_report and before_yesterday_report:
            if not hisWeekNewPercent == -1 and not hisWeekNewPercent == "" and not hisWeekNewPercent == -999999:
                hisWeekRateRate = (newPercent - hisWeekNewPercent) / hisWeekNewPercent
                if hisWeekRateRate > 0 :
                    hisWeekRateRate = "↑{}%".format(int(hisWeekRateRate*100))
                else:
                    hisWeekRateRate = "↓{}%".format(int(-100*hisWeekRateRate))

            if not hisNewPercent == -1 and not hisNewPercent == "" and not hisNewPercent == -999999:
                hisRateRate = (newPercent - hisNewPercent) / hisNewPercent
                if hisRateRate > 0 :
                    hisRateRate = "↑{}%".format(int(hisRateRate*100))
                else:
                    hisRateRate = "↓{}%".format(int(-100*hisRateRate))


            if not hisNewSingle == 0 and not hisOldSingle == 0 and not hisNewSingle == -1 and not hisOldSingle == -1 and not hisOldSingle == -999999 and not hisNewSingle == -999999 and not newSingle == -999999 and not oldSingle == -999999 and not newSingle == -1 and not oldSingle == -1:
                if newSingle >= hisNewSingle:
                    hisNewSingleRate = int((newSingle - hisNewSingle) / hisNewSingle * 100)
                    hisNewSingleRate = "↑{}%".format(hisNewSingleRate)
                else:
                    hisNewSingleRate = int((hisNewSingle - newSingle) / hisNewSingle * 100)
                    hisNewSingleRate = "↓{}%".format(hisNewSingleRate)

                if oldSingle >= hisOldSingle:
                    hisOldSingleRate = int((oldSingle - hisOldSingle) / hisOldSingle * 100)
                    hisOldSingleRate = "↑{}%".format(hisOldSingleRate)
                else:
                    hisOldSingleRate = int((hisOldSingle - oldSingle) / hisOldSingle * 100)
                    hisOldSingleRate = "↓{}%".format(hisOldSingleRate)




        if yesterday_report and before_week_report:
            if not hisWeekNewSingle == 0 and not hisWeekOldSingle == 0 and not hisWeekNewSingle == -1 and not hisWeekOldSingle == -1 and not hisWeekOldSingle == -999999 and not hisWeekNewSingle == -999999 and not newSingle == -999999 and not oldSingle == -999999 and not newSingle == -1 and not oldSingle == -1:
                if newSingle >= hisWeekNewSingle:
                    hisWeekNewSingleRate = int((newSingle - hisWeekNewSingle) / hisWeekNewSingle * 100)
                    hisWeekNewSingleRate = "↑{}%".format(hisWeekNewSingleRate)
                else:
                    hisWeekNewSingleRate = int((hisWeekNewSingle - newSingle) / hisWeekNewSingle * 100)
                    hisWeekNewSingleRate = "↓{}%".format(hisWeekNewSingleRate)

                if oldSingle >= hisWeekOldSingle:
                    hisWeekOldSingleRate = int((oldSingle - hisWeekOldSingle) / hisWeekOldSingle * 100)
                    hisWeekOldSingleRate = "↑{}%".format(hisWeekOldSingleRate)
                else:
                    hisWeekOldSingleRate = int((hisWeekOldSingle - oldSingle) / hisWeekOldSingle * 100)
                    hisWeekOldSingleRate = "↓{}%".format(hisWeekOldSingleRate)
        newOldCustomer = dict(
            newSingle = newSingle if not newSingle == -1 else "" ,
            oldSingle = oldSingle if not oldSingle == -1 else "" ,
            newPercent = str(int(newPercent*100)) + "%" if not newPercent == -1 and not newPercent == "" and not newPercent == -999999 else "" ,
            oldPercent = str(int(oldPercent*100)) + "%" if not oldPercent == -1 and not oldPercent == "" and not oldPercent == -999999 else "" ,
            hisNewSingle = hisNewSingle if not hisNewSingle == -1 else "" ,
            hisOldSingle = hisOldSingle if not hisOldSingle == -1 else "" ,
            hisNewPercent = str(int(hisNewPercent*100)) + "%" if not hisNewPercent == -1 and not hisNewPercent == "" and not hisNewPercent == -999999 else "" ,
            hisOldPercent = str(int(hisOldPercent*100)) + "%" if not hisOldPercent == -1 and not hisOldPercent == "" and not hisOldPercent == -999999 else "" ,
            hisWeekNewSingle = hisWeekNewSingle if not hisWeekNewSingle == -1 else "" ,
            hisWeekOldSingle = hisWeekOldSingle if not hisWeekOldSingle == -1 else "" ,
            hisWeekNewPercent = str(int(hisWeekNewPercent*100)) + "%" if not hisWeekNewPercent == -1 and not hisWeekNewPercent == '' and not hisWeekNewPercent == -999999 else "" ,
            hisWeekOldPercent = str(int(hisWeekOldPercent*100)) + "%" if not hisWeekOldPercent == -1 and not hisWeekOldPercent == '' and not hisWeekOldPercent == -999999 else "" ,

            hisNewSingleRate = hisNewSingleRate,
            hisOldSingleRate = hisOldSingleRate,
            hisWeekNewSingleRate = hisWeekNewSingleRate,
            hisWeekOldSingleRate = hisWeekOldSingleRate,

            hisRateRate = hisRateRate,
            hisWeekRateRate = hisWeekRateRate,
        )
        '''
            客流分析
        '''
        exposureNum = ''
        visitNum = ''
        orderNum = ''
        visitRate = ''
        orderRate = ''

        hisExposureNum = ''
        hisVisitRate = ''
        hisOrderRate = ''

        hisWeekExposureNum = ''
        hisWeekVisitRate = ''
        hisWeekOrderRate = ''

        peerExposureNum = ''
        peerVisitRate = ''
        peerOrderRate = ''
        hisPeerExposureNum = ''
        hisPeerVisitRate = ''
        hisPeerOrderRate = ''
        if yesterday_report:
            exposureNum = yesterday_report.exposureNum
            visitNum = yesterday_report.visitNum
            orderNum = yesterday_report.orderNum
            visitRate = yesterday_report.visitRate
            orderRate = yesterday_report.orderRate
            peerExposureNum = yesterday_report.peerExposureNum
            peerVisitRate = yesterday_report.peerVisitRate
            peerOrderRate = yesterday_report.peerOrderRate

        if before_yesterday_report:
            hisExposureNum = before_yesterday_report.exposureNum
            hisVisitRate = before_yesterday_report.visitRate
            hisOrderRate = before_yesterday_report.orderRate
            hisPeerExposureNum = before_yesterday_report.peerExposureNum
            hisPeerVisitRate = before_yesterday_report.peerVisitRate
            hisPeerOrderRate = before_yesterday_report.peerOrderRate

        if before_week_report:
            hisWeekExposureNum = before_week_report.exposureNum
            hisWeekVisitRate = before_week_report.visitRate
            hisWeekOrderRate = before_week_report.orderRate

        hisVisitRateRate = ''
        hisOrderRateRate = ''
        hisWeekVisitRateRate = ''
        hisWeekOrderRateRate = ''

        peerExposureNumRate = ''
        peerVisitRateRate = ''
        peerOrderRateRate = ''
        if yesterday_report and before_yesterday_report:
            if hisVisitRate != 0:
                if visitRate >= hisVisitRate:
                    hisVisitRateRate = int((visitRate - hisVisitRate) / hisVisitRate * 100)
                    hisVisitRateRate = "提升{}%".format(hisVisitRateRate)
                else:
                    hisVisitRateRate = int((hisVisitRate - visitRate) / hisVisitRate * 100)
                    hisVisitRateRate = "降低{}%".format(hisVisitRateRate)
            if hisOrderRate != 0 :
                if orderRate >= hisOrderRate:
                    hisOrderRateRate = int((orderRate - hisOrderRate) / hisOrderRate * 100)
                    hisOrderRateRate = "提升{}%".format(hisOrderRateRate)
                else:
                    hisOrderRateRate = int((hisOrderRate - orderRate) / hisOrderRate * 100)
                    hisOrderRateRate = "降低{}%".format(hisOrderRateRate)

            if not peerExposureNum == -1 and not hisPeerExposureNum == -1 and hisPeerExposureNum != 0:
                if peerExposureNum >= hisPeerExposureNum:
                    peerExposureNumRate = int((peerExposureNum - hisPeerExposureNum) / hisPeerExposureNum * 100)
                    peerExposureNumRate = "提升{}%".format(peerExposureNumRate)
                else:
                    peerExposureNumRate = int((hisPeerExposureNum - peerExposureNum) / hisPeerExposureNum * 100)
                    peerExposureNumRate = "降低{}%".format(peerExposureNumRate)

            if not peerVisitRate == -1 and not hisPeerVisitRate == -1 and not hisPeerVisitRate == 0:
                if peerVisitRate >= hisPeerVisitRate:
                    peerVisitRateRate = int((peerVisitRate - hisPeerVisitRate) / hisPeerVisitRate * 100)
                    peerVisitRateRate = "提升{}%".format(peerVisitRateRate)
                else:
                    peerVisitRateRate = int((hisPeerVisitRate - peerVisitRate) / hisPeerVisitRate * 100)
                    peerVisitRateRate = "降低{}%".format(peerVisitRateRate)
            if not peerOrderRate == -1 and not hisPeerOrderRate == -1 and not hisPeerOrderRate == -1:
                if peerOrderRate >= hisPeerOrderRate:
                    peerOrderRateRate = int((peerOrderRate - hisPeerOrderRate) / hisPeerOrderRate * 100)
                    peerOrderRateRate = "提升{}%".format(peerOrderRateRate)
                else:
                    peerOrderRateRate = int((hisPeerOrderRate - peerOrderRate) / hisPeerOrderRate * 100)
                    peerOrderRateRate = "降低{}%".format(peerOrderRateRate)

        if yesterday_report and before_week_report:
            if hisWeekVisitRate != 0:
                if visitRate >= hisWeekVisitRate:
                    hisWeekVisitRateRate = int((visitRate - hisWeekVisitRate) / hisWeekVisitRate * 100)
                    hisWeekVisitRateRate = "提升{}%".format(hisWeekVisitRateRate)
                else:
                    hisWeekVisitRateRate = int((hisWeekVisitRate - visitRate) / hisWeekVisitRate * 100)
                    hisWeekVisitRateRate = "降低{}%".format(hisWeekVisitRateRate)

            if hisWeekOrderRate != 0:
                if orderRate >= hisWeekOrderRate:
                    hisWeekOrderRateRate = int((orderRate - hisWeekOrderRate) / hisWeekOrderRate * 100)
                    hisWeekOrderRateRate = "提升{}%".format(hisWeekOrderRateRate)
                else:
                    hisWeekOrderRateRate = int((hisWeekOrderRate - orderRate) / hisWeekOrderRate * 100)
                    hisWeekOrderRateRate = "降低{}%".format(hisWeekOrderRateRate)

        customerTrend = dict(
            exposureNum = exposureNum,
            visitNum = visitNum,
            orderNum = orderNum,
            visitRate = str(int(visitRate*100)) + "%" if visitRate != "" else "" ,
            orderRate = str(int(orderRate*100)) + "%" if orderRate != "" else "" ,

            hisExposureNum = hisExposureNum,
            hisVisitRate = str(int(hisVisitRate*100)) + "%" if hisVisitRate != "" else "" ,
            hisOrderRate = str(int(hisOrderRate*100)) + "%" if hisOrderRate != "" else "" ,

            hisWeekExposureNum = hisWeekExposureNum,
            hisWeekVisitRate = str(int(hisWeekVisitRate*100)) + "%" if hisWeekVisitRate != "" else "" ,
            hisWeekOrderRate = str(int(hisWeekOrderRate*100)) + "%" if hisWeekOrderRate != "" else "" ,

            peerExposureNum = int(peerExposureNum) if not peerExposureNum == '' else '' ,
            peerVisitRate = str(int(peerVisitRate*100)) + "%" if peerVisitRate != "" else "" ,
            peerOrderRate = str(int(peerOrderRate*100)) + "%" if peerOrderRate != "" else "" ,

            hisExposureNumRate = hisExposureNumRate,
            hisWeekExposureNumRate = hisWeekExposureNumRate,
            peerExposureNumRate =  peerExposureNumRate,

            hisVisitRateRate = hisVisitRateRate,
            hisWeekVisitRateRate = hisWeekVisitRateRate,
            peerVisitRateRate = peerVisitRateRate,

            hisOrderRateRate = hisOrderRateRate,
            hisWeekOrderRateRate = hisWeekOrderRateRate,
            peerOrderRateRate = peerOrderRateRate,
        )

        '''
            顾客来源分析
        '''
        bizListExposureNum = ''
        otherExposureNum = ''
        searchExposureNum = ''
        orderPageExposureNum = ''
        selectForUExposureNum = ''

        hisBizListExposureNum = ''
        hisBizListExposureNumRate = ''
        hisOtherExposureNum = ''
        hisOtherExposureNumRate = ''
        hisSearchExposureNum = ''
        hisSearchExposureNumRate = ''
        hisOrderPageExposureNum = ''
        hisOrderPageExposureNumRate = ''
        hisSelectForUExposureNum = ''
        hisSelectForUExposureNumRate = ''

        hisWeekBizListExposureNum = ''
        hisWeekBizListExposureNumRate = ''
        hisWeekOtherExposureNum = ''
        hisWeekOtherExposureNumRate = ''
        hisWeekSearchExposureNum = ''
        hisWeekSearchExposureNumRate = ''
        hisWeekOrderPageExposureNum = ''
        hisWeekOrderPageExposureNumRate = ''
        hisWeekSelectForUExposureNum = ''
        hisWeekSelectForUExposureNumRate = ''

        peerBizListExposureNum = ''
        peerOtherExposureNum = ''
        peerSearchExposureNum = ''
        peerOrderPageExposureNum = ''
        peerSelectForUExposureNum = ''

        if yesterday_report:
            bizListExposureNum = yesterday_report.bizListExposureNum
            otherExposureNum = yesterday_report.otherExposureNum
            searchExposureNum = yesterday_report.searchExposureNum
            orderPageExposureNum = yesterday_report.orderPageExposureNum
            selectForUExposureNum = yesterday_report.selectForUExposureNum
            peerBizListExposureNum = yesterday_report.peerBizListExposureNum
            peerOtherExposureNum = yesterday_report.peerOtherExposureNum
            peerSearchExposureNum = yesterday_report.peerSearchExposureNum
            peerOrderPageExposureNum = yesterday_report.peerOrderPageExposureNum
            peerSelectForUExposureNum = yesterday_report.peerSelectForUExposureNum
        if before_yesterday_report:
            hisBizListExposureNum = before_yesterday_report.bizListExposureNum
            hisOtherExposureNum = before_yesterday_report.otherExposureNum
            hisSearchExposureNum = before_yesterday_report.searchExposureNum
            hisOrderPageExposureNum = before_yesterday_report.orderPageExposureNum
            hisSelectForUExposureNum = before_yesterday_report.selectForUExposureNum
        if before_week_report:
            hisWeekBizListExposureNum = before_week_report.bizListExposureNum
            hisWeekOtherExposureNum = before_week_report.otherExposureNum
            hisWeekSearchExposureNum = before_week_report.searchExposureNum
            hisWeekOrderPageExposureNum = before_week_report.orderPageExposureNum
            hisWeekSelectForUExposureNum = before_week_report.selectForUExposureNum
        if yesterday_report and before_yesterday_report:
            if bizListExposureNum != -1 and hisBizListExposureNum != -1 and hisBizListExposureNum != 0:
                if bizListExposureNum >= hisBizListExposureNum:
                    hisBizListExposureNumRate = int((bizListExposureNum - hisBizListExposureNum) / hisBizListExposureNum * 100)
                    hisBizListExposureNumRate = "提升{}%".format(hisBizListExposureNumRate)
                else:
                    hisBizListExposureNumRate = int((hisBizListExposureNum - bizListExposureNum) / hisBizListExposureNum * 100)
                    hisBizListExposureNumRate = "降低{}%".format(hisBizListExposureNumRate)
            if otherExposureNum != -1 and hisOtherExposureNum != -1 and hisOtherExposureNum != 0:
                if otherExposureNum >= hisOtherExposureNum:
                    hisOtherExposureNumRate = int((otherExposureNum - hisOtherExposureNum) / hisOtherExposureNum * 100)
                    hisOtherExposureNumRate = "提升{}%".format(hisOtherExposureNumRate)
                else:
                    hisOtherExposureNumRate = int((hisOtherExposureNum - otherExposureNum) / hisOtherExposureNum * 100)
                    hisOtherExposureNumRate = "降低{}%".format(hisOtherExposureNumRate)

            if searchExposureNum != -1 and hisSearchExposureNum != -1 and hisSearchExposureNum != 0:
                if searchExposureNum >= hisSearchExposureNum:
                    hisSearchExposureNumRate = int((searchExposureNum - hisSearchExposureNum) / hisSearchExposureNum * 100)
                    hisSearchExposureNumRate = "提升{}%".format(hisSearchExposureNumRate)
                else:
                    hisSearchExposureNumRate = int((hisSearchExposureNum - searchExposureNum) / hisSearchExposureNum * 100)
                    hisSearchExposureNumRate = "降低{}%".format(hisSearchExposureNumRate)

            if orderPageExposureNum != -1 and hisOrderPageExposureNum != -1 and hisOrderPageExposureNum != 0:
                if orderPageExposureNum >= hisOrderPageExposureNum:
                    hisOrderPageExposureNumRate = int((orderPageExposureNum - hisOrderPageExposureNum) / hisOrderPageExposureNum * 100)
                    hisOrderPageExposureNumRate = "提升{}%".format(hisOrderPageExposureNumRate)
                else:
                    hisOrderPageExposureNumRate = int((hisOrderPageExposureNum - orderPageExposureNum) / hisOrderPageExposureNum * 100)
                    hisOrderPageExposureNumRate = "降低{}%".format(hisOrderPageExposureNumRate)
            if selectForUExposureNum != -1 and hisSelectForUExposureNum != -1 and hisSelectForUExposureNum != 0:
                if selectForUExposureNum >= hisSelectForUExposureNum:
                    hisSelectForUExposureNumRate = int((selectForUExposureNum - hisSelectForUExposureNum) / hisSelectForUExposureNum * 100)
                    hisSelectForUExposureNumRate = "提升{}%".format(hisSelectForUExposureNumRate)
                else:
                    hisSelectForUExposureNumRate = int((hisSelectForUExposureNum - selectForUExposureNum) / hisSelectForUExposureNum * 100)
                    hisSelectForUExposureNumRate = "降低{}%".format(hisSelectForUExposureNumRate)
        if yesterday_report and before_week_report:
            if  bizListExposureNum != -1 and hisWeekBizListExposureNum != -1 and hisWeekBizListExposureNum != 0:
                if bizListExposureNum >= hisWeekBizListExposureNum:
                    hisWeekWeekBizListExposureNumRate = int((bizListExposureNum - hisWeekBizListExposureNum) / hisWeekBizListExposureNum * 100)
                    hisWeekWeekBizListExposureNumRate = "提升{}%".format(hisWeekBizListExposureNumRate)
                else:
                    hisWeekBizListExposureNumRate = int((hisWeekBizListExposureNum - bizListExposureNum) / hisWeekBizListExposureNum * 100)
                    hisWeekBizListExposureNumRate = "降低{}%".format(hisWeekBizListExposureNumRate)
            if otherExposureNum != -1 and hisWeekOtherExposureNum != -1 and hisWeekOtherExposureNum != 0:
                if otherExposureNum >= hisWeekOtherExposureNum:
                    hisWeekOtherExposureNumRate = int((otherExposureNum - hisWeekOtherExposureNum) / hisWeekOtherExposureNum * 100)
                    hisWeekOtherExposureNumRate = "提升{}%".format(hisWeekOtherExposureNumRate)
                else:
                    hisWeekOtherExposureNumRate = int((hisWeekOtherExposureNum - otherExposureNum) / hisWeekOtherExposureNum * 100)
                    hisWeekOtherExposureNumRate = "降低{}%".format(hisWeekOtherExposureNumRate)

            if searchExposureNum != -1 and hisWeekSearchExposureNum != -1 and hisWeekSearchExposureNum != 0:
                if searchExposureNum >= hisWeekSearchExposureNum:
                    hisWeekSearchExposureNumRate = int((searchExposureNum - hisWeekSearchExposureNum) / hisWeekSearchExposureNum * 100)
                    hisWeekSearchExposureNumRate = "提升{}%".format(hisWeekSearchExposureNumRate)
                else:
                    hisWeekSearchExposureNumRate = int((hisWeekSearchExposureNum - searchExposureNum) / hisWeekSearchExposureNum * 100)
                    hisWeekSearchExposureNumRate = "降低{}%".format(hisWeekSearchExposureNumRate)

            if orderPageExposureNum != -1 and hisWeekOrderPageExposureNum != -1 and hisWeekOrderPageExposureNum != 0:
                if orderPageExposureNum >= hisWeekOrderPageExposureNum:
                    hisWeekOrderPageExposureNumRate = int((orderPageExposureNum - hisWeekOrderPageExposureNum) / hisWeekOrderPageExposureNum * 100)
                    hisWeekOrderPageExposureNumRate = "提升{}%".format(hisWeekOrderPageExposureNumRate)
                else:
                    hisWeekOrderPageExposureNumRate = int((hisWeekOrderPageExposureNum - orderPageExposureNum) / hisWeekOrderPageExposureNum * 100)
                    hisWeekOrderPageExposureNumRate = "降低{}%".format(hisWeekOrderPageExposureNumRate)
            if selectForUExposureNum != -1 and hisWeekSelectForUExposureNum != -1 and hisWeekSelectForUExposureNum != 0:
                if selectForUExposureNum >= hisWeekSelectForUExposureNum:
                    hisWeekSelectForUExposureNumRate = int((selectForUExposureNum - hisWeekSelectForUExposureNum) / hisWeekSelectForUExposureNum * 100)
                    hisWeekSelectForUExposureNumRate = "提升{}%".format(hisWeekSelectForUExposureNumRate)
                else:
                    hisWeekSelectForUExposureNumRate = int((hisWeekSelectForUExposureNum - selectForUExposureNum) / hisWeekSelectForUExposureNum * 100)
                    hisWeekSelectForUExposureNumRate = "降低{}%".format(hisWeekSelectForUExposureNumRate)

        customerSource = []
        item1 = dict()
        item1["name"] = "商家列表"
        item1["exposureNum"] = bizListExposureNum
        item1["hisExposureNum"] = hisBizListExposureNum if hisBizListExposureNum != -1 else ''
        item1["hisWeekExposureNum"] = hisWeekBizListExposureNum if hisWeekBizListExposureNum != -1 else ''
        item1["peerExposureNum"] = peerBizListExposureNum
        item1["hisExposureNumRate"] = hisBizListExposureNumRate
        item1["hisWeekExposureNumRate"] = hisWeekBizListExposureNumRate

        item2 = dict()
        item2["name"] = "其他"
        item2["exposureNum"] = otherExposureNum
        item2["hisExposureNum"] = hisOtherExposureNum if hisOtherExposureNum != -1 else ''
        item2["hisWeekExposureNum"] = hisWeekOtherExposureNum if hisWeekOtherExposureNum != -1 else ''
        item2["peerExposureNum"] = peerOtherExposureNum
        item2["hisExposureNumRate"] = hisOtherExposureNumRate
        item2["hisWeekExposureNumRate"] = hisWeekOtherExposureNumRate

        item3 = dict()
        item3["name"] = "搜索"
        item3["exposureNum"] = searchExposureNum
        item3["hisExposureNum"] = hisSearchExposureNum if hisSearchExposureNum != -1 else ''
        item3["hisWeekExposureNum"] = hisWeekSearchExposureNum if hisWeekSearchExposureNum != -1 else ''
        item3["peerExposureNum"] = peerSearchExposureNum
        item3["hisExposureNumRate"] = hisSearchExposureNumRate
        item3["hisWeekExposureNumRate"] = hisWeekSearchExposureNumRate

        item4 = dict()
        item4["name"] = "订单页面"
        item4["exposureNum"] = orderPageExposureNum
        item4["hisExposureNum"] = hisOrderPageExposureNum if hisOrderPageExposureNum != -1 else ''
        item4["hisWeekExposureNum"] = hisWeekOrderPageExposureNum if hisWeekOrderPageExposureNum != -1 else ''
        item4["peerExposureNum"] = peerOrderPageExposureNum
        item4["hisExposureNumRate"] = hisOrderPageExposureNumRate
        item4["hisWeekExposureNumRate"] = hisWeekOrderPageExposureNumRate

        item5 = dict()
        item5["name"] = "为你优选"
        item5["exposureNum"] = selectForUExposureNum
        item5["hisExposureNum"] = hisSelectForUExposureNum if hisSelectForUExposureNum != -1 else ''
        item5["hisWeekExposureNum"] = hisWeekSelectForUExposureNum if hisWeekSelectForUExposureNum != -1 else ''
        item5["peerExposureNum"] = peerSelectForUExposureNum
        item5["hisExposureNumRate"] = hisSelectForUExposureNumRate
        item5["hisWeekExposureNumRate"] = hisWeekSelectForUExposureNumRate

        customerSource.append(item1)
        customerSource.append(item2)
        customerSource.append(item3)
        customerSource.append(item4)
        customerSource.append(item5)
        #排序
        for m in range(len(customerSource)):
            for n in range(m+1, len(customerSource)):
                if customerSource[m].get("exposureNum") >  customerSource[n].get("exposureNum"):
                    temp = deepcopy(customerSource[m])
                    customerSource[m] = deepcopy(customerSource[n])
                    customerSource[n] = temp

        customerSource = list(reversed(customerSource))
        '''
            商家评分 
        '''
        scoreList = []

        week_report = list(reversed(week_report))
        for day in week_report:
            scoreList.append(day.score)

        '''
            进俩天星级评论
        '''
        commentLevel = {}
        if yesterday_report:
            yes_comment_star = yesterday_report.commentStarInfo
            commentLevel["yesterday"] = eval(yes_comment_star)
        if before_yesterday_report:
            before_yes_star = before_yesterday_report.commentStarInfo
            commentLevel["beforeYesterday"] = eval(before_yes_star)

        '''
            cpc Exposure analyse
            实际周期曝光，2小时一次
        '''
        try:
            res = getPriceCount(shopId, shopType, yesterday + ' 00:00:00')
            periodExposure = res.get("periodExposure")
            avgPrice = res.get("masterData").get("avgPrice")
            maxPrice = res.get("masterData").get("maxPrice")
            minPrice = res.get("masterData").get("minPrice")
            yesterdayCPCExposure = [0 for i in range(24)]
            yesterdayAvgPrice = [0 for i in range(24)]
            yesterdayMaxPrice = [0 for i in range(24)]
            yesterdayMinPrice = [0 for i in range(24)]
            count = 0
            index = 0
            for i in range(len(periodExposure)):
                yesterdayCPCExposure[index] += periodExposure[i]
                yesterdayAvgPrice[index] += avgPrice[i]
                yesterdayMaxPrice[index] += maxPrice[i]
                yesterdayMinPrice[index] += minPrice[i]
                count += 1
                if count == 2:
                    count = 0
                    yesterdayMaxPrice[index] = round(yesterdayMaxPrice[index], 2)
                    yesterdayMinPrice[index] = round(yesterdayMinPrice[index], 2)
                    index += 1
            yesterdayAvgPrice = [round(i / 2, 2) for i in yesterdayAvgPrice]
            yesterdayMaxPrice = [round(i / 2, 2) for i in yesterdayMaxPrice]
            yesterdayMinPrice = [round(i / 2, 2) for i in yesterdayMinPrice]

            res = getPriceCount(shopId, shopType, before_yesterday + ' 00:00:00')
            periodExposure = res.get("periodExposure")

            avgPrice = res.get("masterData").get("avgPrice")
            maxPrice = res.get("masterData").get("maxPrice")
            minPrice = res.get("masterData").get("minPrice")

            beforeYesterdayCPCExposure = [0 for i in range(24)]
            beforeYesterdayAvgPrice = [0 for i in range(24)]
            beforeYesterdayMaxPrice = [0 for i in range(24)]
            beforeYesterdayMinPrice = [0 for i in range(24)]
            count = 0
            index = 0
            for i in range(len(periodExposure)):
                beforeYesterdayCPCExposure[index] += periodExposure[i]
                beforeYesterdayAvgPrice[index] += avgPrice[i]
                beforeYesterdayMaxPrice[index] += maxPrice[i]
                beforeYesterdayMinPrice[index] += minPrice[i]
                count += 1
                if count == 2:
                    count = 0
                    beforeYesterdayMaxPrice[index] = round(beforeYesterdayMaxPrice[index], 2)
                    beforeYesterdayMinPrice[index] = round(beforeYesterdayMinPrice[index], 2)
                    index += 1
            beforeYesterdayAvgPrice = [round(i / 2, 2) for i in beforeYesterdayAvgPrice]
            beforeYesterdayMaxPrice = [round(i / 2, 2) for i in beforeYesterdayMaxPrice]
            beforeYesterdayMinPrice = [round(i / 2, 2) for i in beforeYesterdayMinPrice]

            res = getPriceCount(shopId, shopType, before_week + ' 00:00:00')
            periodExposure = res.get("periodExposure")
            avgPrice = res.get("masterData").get("avgPrice")
            maxPrice = res.get("masterData").get("maxPrice")
            minPrice = res.get("masterData").get("minPrice")
            beforeWeekCPCExposure = [0 for i in range(24)]
            beforeWeekAvgPrice = [0 for i in range(24)]
            beforeWeekMaxPrice = [0 for i in range(24)]
            beforeWeekMinPrice = [0 for i in range(24)]
            count = 0
            index = 0
            for i in range(len(periodExposure)):
                beforeWeekCPCExposure[index] += periodExposure[i]
                beforeWeekAvgPrice[index] += avgPrice[i]
                beforeWeekMaxPrice[index] += maxPrice[i]
                beforeWeekMinPrice[index] += minPrice[i]
                count += 1
                if count == 2:
                    count = 0
                    beforeWeekMaxPrice[index] = round(beforeWeekMaxPrice[index] , 2)
                    beforeWeekMinPrice[index] = round(beforeWeekMinPrice[index] , 2)
                    index += 1
            beforeWeekAvgPrice = [round(i / 2, 2) for i in beforeWeekAvgPrice]
            beforeWeekMaxPrice = [round(i / 2, 2) for i in beforeWeekMaxPrice]
            beforeWeekMinPrice = [round(i / 2, 2) for i in beforeWeekMinPrice]

            avgPrice = {"yesterdayAvgPrice" : yesterdayAvgPrice,
                        "yesterdayMaxPrice" : yesterdayMaxPrice,
                        "yesterdayMinPrice" : yesterdayMinPrice,
                        "beforeYesterdayAvgPrice" : beforeYesterdayAvgPrice ,
                        "beforeYesterdayMaxPrice" : beforeYesterdayMaxPrice,
                        "beforeYesterdayMinPrice" : beforeYesterdayMinPrice,
                        "beforeWeekMaxPrice":beforeWeekMaxPrice,
                        "beforeWeekMinPrice" : beforeWeekMinPrice,
                        "beforeWeekAvgPrice" : beforeWeekAvgPrice}
            CPCExposureAnalyse = {"yesterdayCPCExposure" : yesterdayCPCExposure,"beforeYesterdayCPCExposure" : beforeYesterdayCPCExposure, "beforeWeekCPCExposure" : beforeWeekCPCExposure}
        except:
            avgPrice = {"yesterdayAvgPrice": "",
                        "yesterdayMaxPrice": "",
                        "yesterdayMinPrice": "",
                        "beforeYesterdayAvgPrice": "",
                        "beforeYesterdayMaxPrice": "",
                        "beforeYesterdayMinPrice": "",
                        "beforeWeekMaxPrice": "",
                        "beforeWeekMinPrice": "",
                        "beforeWeekAvgPrice": "",}
            CPCExposureAnalyse = {"yesterdayCPCExposure": "",
                                  "beforeYesterdayCPCExposure": "",
                                  "beforeWeekCPCExposure": "",}

        '''
            订单数分析
        '''
        result = getReportOrderAnalyse(shopId, shopType, yesterday, before_yesterday, before_week)


        '''
            活动分析
            活动失效
        '''
        changedActivity = [{"name" : "满减" , "hasChange" : False},
                           {"name" : "折扣商品" , "hasChange" : False},
                           {"name" : "新用户立减" , "hasChange" : False},
                           {"name" : "门店新客立减" , "hasChange" : False},
                           {"name" : "满赠" , "hasChange" : False}
                           ]
        invalidActivity = [{"name" : "满减" , "hasInvalidActivity" : False},
                           {"name" : "折扣商品" , "hasInvalidActivity" : False},
                           {"name" : "新用户立减" , "hasInvalidActivity" : False},
                           {"name" : "门店新客立减" , "hasInvalidActivity" : False},
                           {"name" : "满赠" , "hasInvalidActivity" : False}
                           ]
        activityName = ["满减", "折扣商品" , "新用户立减" , "门店新用户立减" , "满赠"]
        if yesterday_report and before_yesterday_report and yesterday_report.activity and before_yesterday_report.activity:
            activity1 = yesterday_report.activity
            activity2 = before_yesterday_report.activity
            activity1 = demjson.decode(activity1)
            activity2 = demjson.decode(activity2)

            for act1 in activity1:
                if act1.get("name") in activityName:
                    res = analyseActivity(act1.get("name"), act1.get("detail"), activity2)
                    if res.get("flag") == 1 and res.get("oldActivityInvalid"):
                        activityId = activityName.index(act1.get("name"))
                        invalidActivity[activityId]["invalidActDetail"] = res.get("oldActivity").replace("<br>", ";")
                        invalidActivity[activityId]["hasInvalidActivity"] = True
                        changedActivity[activityId]["originalActivity"] = act1.get("detail").replace("<br>", ";")
                        changedActivity[activityId]["newActivity"] = res.get("oldActivity").replace("<br>", ";")
                        changedActivity[activityId]["hasChange"] = True

        myActivity = []
        '''我的所有活动及剩余天数'''
        if yesterday_report:
            activities = yesterday_report.activity
            activities = demjson.decode(activities)
            for act in activities:
                startTime = act.get("startTime")
                endTime = act.get("endTime")
                nowTime = int(time.time())
                daysNum = int((endTime - nowTime) / 24 / 60 / 60)
                if daysNum > 0 :
                    myActivity.append({"name" : act.get("name") , "detail" : act.get("detail").replace("<br>", ";") , "remainingDaysNum" : daysNum + 1})

        '''
            复购
        '''
        allRepeat = ''
        allRepeatRate = ''
        allRepeatCompareLastWeek = ''
        allRepeatCompareLastMonth = ''
        newRepeat = ''
        newRepeatRate = ''
        newRepeatCompareLastWeek = ''
        newRepeatCompareLastMonth = ''
        oldRepeat = ''
        oldRepeatRate = ''
        oldRepeatCompareLastWeek = ''
        oldRepeatCompareLastMonth = ''
        repeatInfo = dict(
            lastWeekAllRepeat="",
            lastMonthAllRepeat="",
            lastWeekNewRepeat="",
            lastMonthNewRepeat="",
            lastWeekOldRepeat="",
            lastMonthOldRepeat="",
            allRepeat="",
            allRepeatRate="",
            allRepeatCompareLastWeek="",
            allRepeatCompareLastMonth="",
            newRepeat="",
            newRepeatRate="",
            newRepeatCompareLastWeek="",
            newRepeatCompareLastMonth="",
            oldRepeat="",
            oldRepeatRate="",
            oldRepeatCompareLastWeek="",
            oldRepeatCompareLastMonth="",
        )
        if yesterday_report:
            if yesterday_report.allRepeat and yesterday_report.allRepeatCompareLastWeek and yesterday_report.newRepeat:


                lastMonthOldRepeat = ""
                oldRepeatCompareLastMonth = ""
                if yesterday_report.oldRepeatCompareLastMonth and  yesterday_report.oldRepeatCompareLastMonth != -999999:
                    lastMonthOldRepeat = int(yesterday_report.oldRepeat / (1 + yesterday_report.oldRepeatCompareLastMonth))
                    oldRepeatCompareLastMonth = '↑ {}%'.format(
                        int(yesterday_report.oldRepeatCompareLastMonth * 100)) if yesterday_report.oldRepeatCompareLastMonth > 0 else '↓ {}%'.format(
                        int(-1 * yesterday_report.oldRepeatCompareLastMonth * 100))

                lastWeekOldRepeat = ''
                oldRepeatCompareLastWeek = ''
                if yesterday_report.oldRepeatCompareLastWeek and  yesterday_report.oldRepeatCompareLastWeek != -999999:
                    lastMonthOldRepeat = int(yesterday_report.oldRepeat / (1 + yesterday_report.oldRepeatCompareLastWeek))
                    oldRepeatCompareLastWeek = '↑ {}%'.format(
                        int(yesterday_report.oldRepeatCompareLastWeek * 100)) if yesterday_report.oldRepeatCompareLastWeek > 0 else '↓ {}%'.format(
                        int(-1 * yesterday_report.oldRepeatCompareLastWeek * 100))

                lastWeekNewRepeat = ''
                newRepeatCompareLastWeek = ''
                if yesterday_report.newRepeatCompareLastWeek and  yesterday_report.newRepeatCompareLastWeek != -999999:
                    lastWeekNewRepeat = int(yesterday_report.newRepeat / (1 + yesterday_report.newRepeatCompareLastWeek))
                    newRepeatCompareLastWeek = '↑ {}%'.format(
                        int(
                            yesterday_report.newRepeatCompareLastWeek * 100)) if yesterday_report.newRepeatCompareLastWeek > 0 else '↓ {}%'.format(
                        int(-1 * yesterday_report.newRepeatCompareLastWeek * 100))

                lastMonthNewRepeat = ''
                newRepeatCompareLastMonth = ''
                if yesterday_report.newRepeatCompareLastMonth and  yesterday_report.newRepeatCompareLastMonth != -999999:
                    lastMonthNewRepeat = int(yesterday_report.newRepeat / (1 + yesterday_report.newRepeatCompareLastMonth))
                    newRepeatCompareLastMonth = '↑ {}%'.format(
                        int(
                            yesterday_report.newRepeatCompareLastMonth * 100)) if yesterday_report.newRepeatCompareLastMonth > 0 else '↓ {}%'.format(
                        int(-1 * yesterday_report.newRepeatCompareLastMonth * 100))

                lastWeekAllRepeat = ''
                allRepeatCompareLastWeek = ''
                if yesterday_report.allRepeatCompareLastWeek and  yesterday_report.allRepeatCompareLastWeek != -999999:
                    lastWeekAllRepeat = int(
                        yesterday_report.allRepeat / (1 + yesterday_report.allRepeatCompareLastWeek))
                    allRepeatCompareLastWeek = '↑ {}%'.format(
                        int(
                            yesterday_report.allRepeatCompareLastWeek * 100)) if yesterday_report.allRepeatCompareLastWeek > 0 else '↓ {}%'.format(
                        int(-1 * yesterday_report.allRepeatCompareLastWeek * 100))

                lastMonthAllRepeat = ''
                allRepeatCompareLastMonth = ''
                if yesterday_report.allRepeatCompareLastMonth and  yesterday_report.allRepeatCompareLastMonth != -999999:
                    lastMonthAllRepeat = int(
                        yesterday_report.allRepeat / (1 + yesterday_report.allRepeatCompareLastMonth))
                    allRepeatCompareLastMonth = '↑ {}%'.format(
                        int(
                            yesterday_report.allRepeatCompareLastMonth * 100)) if yesterday_report.allRepeatCompareLastMonth > 0 else '↓ {}%'.format(
                        int(-1 * yesterday_report.allRepeatCompareLastMonth * 100))


                repeatInfo = dict(
                    lastWeekAllRepeat = lastWeekAllRepeat,
                    lastMonthAllRepeat = lastMonthAllRepeat,
                    lastWeekNewRepeat = lastWeekNewRepeat,
                    lastMonthNewRepeat = lastMonthNewRepeat,
                    lastWeekOldRepeat = lastWeekOldRepeat,
                    lastMonthOldRepeat = lastMonthOldRepeat,

                    allRepeat = yesterday_report.allRepeat,
                    allRepeatRate = str(int(yesterday_report.allRepeatRate*100)) + "%" if yesterday_report.allRepeatRate and yesterday_report.allRepeatRate != -999999 and yesterday_report.allRepeatRate != 0 else "" ,
                    allRepeatCompareLastWeek = allRepeatCompareLastWeek,
                    allRepeatCompareLastMonth = allRepeatCompareLastMonth,
                    newRepeat = yesterday_report.newRepeat,
                    newRepeatRate = str(int(yesterday_report.newRepeatRate*100)) + "%" if yesterday_report.newRepeatRate and yesterday_report.newRepeatRate != -999999 and yesterday_report.allRepeatRate != 0 else "" ,
                    newRepeatCompareLastWeek = newRepeatCompareLastWeek,
                    newRepeatCompareLastMonth = newRepeatCompareLastMonth,
                    oldRepeat = yesterday_report.oldRepeat,
                    oldRepeatRate = str(int(yesterday_report.oldRepeatRate*100)) + "%" if yesterday_report.oldRepeatRate and yesterday_report.oldRepeatRate != -999999 and yesterday_report.allRepeatRate != 0 else "" ,
                    oldRepeatCompareLastWeek = oldRepeatCompareLastWeek,
                    oldRepeatCompareLastMonth = oldRepeatCompareLastMonth,
                )

        return {"reportHeadInfo": reportHeadInfo,

                "dataBoard": dataBoard,
                "orderAnalyse": result,
                "CPCExposureAnalyse": CPCExposureAnalyse,
                "avgPrice": avgPrice,
                "newOldCustomer": newOldCustomer,
                "customerTrendAnalyse": customerTrend,
                "customerSourceAnalyse": customerSource,
                "scoreList": scoreList,
                "commentLevel": commentLevel,
                "myActivity" : myActivity,
                "changedAcitvity" : changedActivity,
                "invalidActivity" : invalidActivity,
                "repeatInfo" : repeatInfo,
                "customerLabelInfo" : customerLabelInfo,
                }
    except:
        logger.info(traceback.format_exc())
        logger.info("运营报告获取出错:美团ID：{}, =_= =_=".format(shopId))
        return False


def getReportOrderAnalyse(shopId, shopType, yesterday, before_yesterday, before_week):

    session = Session()
    if shopType == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        account = shop.account
    else:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.eleId == shopId).first()
        account = shop.account
    yesOrder = session.query(YesOrderInfo).filter(YesOrderInfo.account == account, YesOrderInfo.day == yesterday).first()
    beforeYesOrder = session.query(YesOrderInfo).filter(YesOrderInfo.account == account, YesOrderInfo.day == before_yesterday).first()
    beforeWeekOrder = session.query(YesOrderInfo).filter(YesOrderInfo.account == account, YesOrderInfo.day == before_week).first()
    session.close()
    yes_infoList = [0 for i in range(48)]
    beforeYes_infoList = [0 for i in range(48)]
    beforeWeek_infoList = [0 for i in range(48)]

    if yesOrder and yesOrder.InfoList:
        yes_infoList = eval(yesOrder.InfoList)
    if beforeYesOrder and beforeYesOrder.InfoList:
        beforeYes_infoList = eval(beforeYesOrder.InfoList)
    if beforeWeekOrder and beforeWeekOrder.InfoList:
        beforeWeek_infoList = eval(beforeWeekOrder.InfoList)

    yesOrderList = [0 for i in range(24)]
    beforeYesOrderList = [0 for i in range(24)]
    beforeWeekOrderList = [0 for i in range(24)]

    count = 0
    index = 0
    for i in range(48):
        yesOrderList[index] += yes_infoList[i]
        beforeYesOrderList[index] += beforeYes_infoList[i]
        beforeWeekOrderList[index] += beforeWeek_infoList[i]
        count += 1
        if count == 2:
            count = 0
            index += 1

    yes_beforeYes_orderList = [0 for i in range(24)]
    yes_beforeWeek_orderList = [0 for i in range(24)]
    for i in range(24):
        yes_beforeYes_orderList[i] = yesOrderList[i] - beforeYesOrderList[i]
        yes_beforeWeek_orderList[i] = yesOrderList[i] - beforeWeekOrderList[i]
    return {"yesOrderList" : yesOrderList, "beforeYesOrderList" : beforeYesOrderList, "beforeWeekOrderList" : beforeWeekOrderList,"yes_beforeYes_orderList":yes_beforeWeek_orderList,
            "yes_beforeWeek_orderList" : yes_beforeWeek_orderList}

def analyseActivity(activityName, activityDetail, activity):
    for act in activity:
        if act.get("name") == activityName:
            if not activityDetail == act.get("detail"):
                # 活动改变了,老活动失效了
                return {"flag" : 1, "oldActivityInvalid" : True, "oldActivity" : act.get("detail")}
            else:
                return {"flag": 1, "oldActivityInvalid": False, "oldActivity": act.get("detail")}
    return {"flag": 0, "oldActivityInvalid": False, "oldActivity": ""}


def getReportInfo(shopId, shopType, day):

    try:
        session = Session()
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
        account = shop.account
        targetExposure = shop.targetExposure
        budget = float(shop.budget)

        yesterday = (datetime.datetime.strptime(day, "%Y-%m-%d") + datetime.timedelta(days = -1)).strftime("%Y-%m-%d")
        week = (datetime.datetime.strptime(day, "%Y-%m-%d") + datetime.timedelta(days = -7)).strftime("%Y-%m-%d")
        startTime = day + " 00:00:00"
        endTime = day + " 23:58:00"


        busyTime = []
        idleTime = []
        specialtime = shop.specialtime
        if specialtime:
            specialtime = eval(specialtime)
            for st in specialtime:
                if st.get("type") == 1:
                    busyTime.append(st.get('s') + "-" + st.get("e"))
                else:
                    idleTime.append(st.get('s') + "-" + st.get("e"))

        deadTime = ''
        balance = ''
        effectiveOrders = ''
        status = ''
        income = ''
        invalidOrders = ''

        showCount = ""
        clickCount = ""
        daysAvgClickCount = ""
        avgPrice = ""
        daysAvgPrice = ""

        yesSameTimeEffOrdersNum = ""
        weekSameTimeEffOrdersNum = ""
        lastLog = session.query(ShopBidding).filter(ShopBidding.shopid == shopId, ShopBidding.biddingTime >= startTime, ShopBidding.biddingTime <= endTime).order_by(ShopBidding.id.desc()).all()
        if lastLog:
            lastLog = lastLog[0]
            deadTime = lastLog.biddingTime.split(" ")[1][:5]
            balance = lastLog.blance
            effectiveOrders = int(lastLog.realTimeOrder)
            status = lastLog.shopStatus
            income = lastLog.allExposure
            invalidOrders = lastLog.percentBudget

            showCount = lastLog.exposureNum
            clickCount = lastLog.visitNum
            currentCost = lastLog.currentCost
            exposureNum = int(lastLog.exposureNum) if lastLog.exposureNum else ''
            cost_per_click = currentCost / clickCount if clickCount != 0 else ''


            daysAvgClickCount = lastLog.daysAvgClickCount
            avgPrice = lastLog.avgPrice
            daysAvgPrice = lastLog.daysAvgPrice

            yesterdayNowTime = yesterday + " " + lastLog.biddingTime.split(" ")[1]
            yesterdayNowTime_add = (
                        datetime.datetime.strptime(yesterdayNowTime, "%Y-%m-%d %H:%M:00") + datetime.timedelta(
                    minutes=-1)).strftime("%Y-%m-%d %H:%M:00")
            weekNowTime = week + " " + lastLog.biddingTime.split(" ")[1]
            weekNowTime_add = (datetime.datetime.strptime(weekNowTime, "%Y-%m-%d %H:%M:00") + datetime.timedelta(
                minutes=-1)).strftime("%Y-%m-%d %H:%M:00")

            yesSameTimeEffOrders = session.query(ShopBidding.realTimeOrder).filter(
                or_(ShopBidding.biddingTime == yesterdayNowTime_add,
                    ShopBidding.biddingTime == yesterdayNowTime),ShopBidding.shopid == shopId).first()
            weekSameTimeEffOrders = session.query(ShopBidding.realTimeOrder).filter(
                or_(ShopBidding.biddingTime == weekNowTime_add, ShopBidding.biddingTime == weekNowTime),ShopBidding.shopid == shopId).first()

            if yesSameTimeEffOrders:
                yesSameTimeEffOrdersNum = yesSameTimeEffOrders[0]
                if yesSameTimeEffOrdersNum:
                    yesSameTimeEffOrdersNum = int(float(yesSameTimeEffOrdersNum))

            if weekSameTimeEffOrders:
                weekSameTimeEffOrdersNum = weekSameTimeEffOrders[0]
                if weekSameTimeEffOrdersNum:
                    weekSameTimeEffOrdersNum = int(float(weekSameTimeEffOrdersNum))


        '''效果对比'''

        bestExposure = 0
        bestVisit = 0
        exposureLog = ''
        visitLog = ''
        exposure_rate = ''
        visit_rate = ''

        pre_exposure = 0
        later_exposure = 0
        later_visit = 0
        pre_visit = 0
        owedExposure = 0
        owedVisit = 0
        try:
            biddingDataResult = getBiddingsData(shopId)
            for index, biddingData in list(enumerate(biddingDataResult)):

                if biddingData.get("cha")[0] > bestExposure and biddingData.get("pre")[0] != 0 and \
                        biddingData.get("later")[0] != 0:
                    bestExposure = biddingData.get("cha")[0]
                    later_exposure = biddingData.get("later")[0]
                    pre_exposure = biddingData.get("pre")[0]
                    if pre_exposure != 0 and later_exposure != 0:
                        exposure_rate = (later_exposure - pre_exposure) / pre_exposure
                        exposure_rate = str(round(exposure_rate * 100, 2)) + "%"
                    exposureLog = biddingData.get("log")
                    owedExposure = budget * (
                                later_exposure - pre_exposure) if later_exposure != 0 and pre_exposure != 0 else ''

                if biddingData.get("cha")[1] < bestVisit and biddingData.get("pre")[1] != 0 and \
                        biddingData.get("later")[1] != 0:
                    bestVisit = biddingData.get("cha")[1]
                    visitLog = biddingData.get("log")
                    later_visit = biddingData.get("later")[1]
                    pre_visit = biddingData.get("pre")[1]

                    if pre_visit != 0 and later_visit != 0:
                        visit_rate = (pre_visit - later_visit) / pre_visit
                        visit_rate = str(round(visit_rate * 100, 2)) + "%"
                    owedVisit = budget / later_visit - budget / pre_visit if later_visit != 0 and pre_visit != 0 else ''
            effectsComparison = dict(
                budget=budget,
                exposure_rate=exposure_rate,
                exposure_per_cost=round(later_exposure, 2) if later_exposure != '' else '',
                owedExposure=int(owedExposure) if owedExposure != '' else '',
                visit_rate=visit_rate,
                cost_per_visit=round(later_visit, 2) if later_visit != '' else '',
                owedVisit=int(owedVisit) if owedVisit != '' else '',
            )
        except:
            logger.info(traceback.format_exc())
            effectsComparison = dict(
                budget=0,
                exposure_rate='',
                exposure_per_cost=0,
                owedExposure=0,
                visit_rate='',
                cost_per_visit=0,
                owedVisit=0,
            )


        today = session.query(YesOrderInfo).filter(YesOrderInfo.account == account, YesOrderInfo.day == day).first()
        yesterday = session.query(YesOrderInfo).filter(YesOrderInfo.account == account, YesOrderInfo.day == yesterday).first()
        week = session.query(YesOrderInfo).filter(YesOrderInfo.account == account, YesOrderInfo.day == week).first()
        session.close()
        if today and today.headInfo:
            headInfo = eval(today.headInfo)
            heads = {"item1": {"showCount": headInfo.get('ep').get('o', None),
                               "targetExposure": headInfo.get('ep').get('t', None)},
                     "item2": {"clickCount": headInfo.get('ck').get('o', None),
                               "daysAvgClickCount": headInfo.get('ck').get('s', None)},

                     "item4": {"avgPrice": headInfo.get('pc').get('o', None),
                               "daysAvgPrice": headInfo.get('pc').get('s', None)}}
        else:
            heads = {"item1": {"showCount": showCount, "targetExposure": targetExposure},
                     "item2": {"clickCount":clickCount, "daysAvgClickCount": daysAvgClickCount},
                     "item4": {"avgPrice": avgPrice, "daysAvgPrice": daysAvgPrice}
                     }


        curbidInfo = getPartCurbidInfo(shopId, shopType, day)

        dayPartCurbidInfo = curbidInfo.get("dayPartCurbidInfo")
        yesPartCurbidInfo = curbidInfo.get("yesPartCurbidInfo")
        effOrderPartIterator = getIterator(dayPartCurbidInfo.get("realTimeOrderList"))

        maxPrice = getIterator(dayPartCurbidInfo.get("masterData").get("maxPrice"))
        minPrice = getIterator(dayPartCurbidInfo.get("masterData").get("minPrice"))
        avgPrice = getIterator(dayPartCurbidInfo.get("masterData").get("avgPrice"))
        yesAvgPrice = getIterator(yesPartCurbidInfo.get("masterData").get("avgPrice"))

        maxPrice = [round(i / 2, 2) for i in maxPrice]
        minPrice = [round(i / 2, 2) for i in minPrice]
        avgPrice = [round(i / 2, 2) for i in avgPrice]
        yesAvgPrice = [round(i / 2, 2) for i in yesAvgPrice]

        periodExposure = getIterator(dayPartCurbidInfo.get("periodExposure"))
        yesPeriodExposure = getIterator(yesPartCurbidInfo.get("periodExposure"))
        periodTarget = getPeriodTargetHour(shopId, shopType, day + " 00:00:00")


        yesOrderIterator = [0 for i in range(24)]
        weekOrderIterator = [0 for i in range(24)]

        if yesterday and yesterday.InfoList:
            yesterdayInfoList = eval(yesterday.InfoList)
            yesOrderIterator = getIterator(yesterdayInfoList)

        if week and week.InfoList:
            weekInfoList = eval(week.InfoList)
            weekOrderIterator = getIterator(weekInfoList)

        yesOrderCompareIterator = [0 for i in range(len(effOrderPartIterator))]
        weekOrderCompareIterator = [0 for i in range(len(effOrderPartIterator))]

        for i in range(len(effOrderPartIterator)):
            yesOrderCompareIterator[i] = effOrderPartIterator[i] - yesOrderIterator[i]
            weekOrderCompareIterator[i] = effOrderPartIterator[i] - weekOrderIterator[i]

        return {
            "heads" : heads,
            "deadTime" : deadTime,
            "balance" : balance,
            "cost_per_click" : round(cost_per_click,2) if cost_per_click != 0 and cost_per_click != '' else '',
            "currentCost" : currentCost,
            "exposureNum": exposureNum,
            "effectiveOrders" : effectiveOrders,
            "yesSameTimeEffOrders" : yesSameTimeEffOrdersNum ,
            "weekSameTimeEffOrders" : weekSameTimeEffOrdersNum ,
            "busyTime" : busyTime,
            "idleTime" : idleTime,
            "invalidOrders" : int(float(invalidOrders)),
            "status" : status,
            "income" : float(income),
            "todayOrderIterator" : effOrderPartIterator,
            "yesOrderIterator" : yesOrderIterator,
            "weekOrderIterator" : weekOrderIterator,
            "yesOrderCompareIterator" : yesOrderCompareIterator,
            "weekOrderCompareIterator" : weekOrderCompareIterator,

            "avgPrice" : avgPrice,
            "maxPrice" : maxPrice,
            "minPrice" : minPrice,
            "yesAvgPrice" : yesAvgPrice,

            "periodExposure" : periodExposure,
            "yesPeriodExposure" : yesPeriodExposure,
            "periodTarget" : periodTarget,
            "effectsComparison" : effectsComparison,
        }
    except:
        logger.info(traceback.format_exc())
        logger.info("CPC曝光获取出错:美团ID：{}, =_= =_=".format(shopId))
        return False


def getIterator(list):
    count = 0
    index = 0
    length = len(list) if len(list) % 2 == 0 else len(list) - 1
    iterator = [0 for i in range(int(length / 2))]
    for i in range(length):
        iterator[index] += list[i]
        count += 1
        if count == 2:
            count = 0
            index += 1

    return iterator

def getPartCurbidInfo(sid, shopType, day):
    dayStart = day + " 00:00:00"
    dayEnd = day + " 23:58:00"
    yes = (datetime.datetime.strptime(day, "%Y-%m-%d") + datetime.timedelta(days = -1)).strftime("%Y-%m-%d")
    yesStart = yes + " 00:00:00"
    yesEnd = yes + " 23:58:00"

    session = Session()
    logs = session.query(ShopBidding).filter(ShopBidding.shopid == sid, ShopBidding.biddingTime >= dayStart, ShopBidding.biddingTime <= dayEnd).all()
    yes_logs = session.query(ShopBidding).filter(ShopBidding.shopid == sid, ShopBidding.biddingTime >= yesStart, ShopBidding.biddingTime <= yesEnd).all()
    session.close()

    dayPartCurbidInfo = getPartCurbidDetail(day, logs)
    yesPartCurbidInfo = getPartCurbidDetail(yes, yes_logs)


    return {"dayPartCurbidInfo" : dayPartCurbidInfo, "yesPartCurbidInfo" : yesPartCurbidInfo}
def getPartCurbidDetail(day, logs):

    item2 = []
    nowTime = day + " " + datetime.datetime.now().strftime("%H:%M:%S")

    today = datetime.datetime.strptime(day + " 00:00:00", "%Y-%m-%d %H:%M:%S")
    for i in range(48):
        everyTimeList = []
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        today = today + datetime.timedelta(minutes=30)
        everyTimeList.append(today.strftime("%Y-%m-%d %H:%M:%S"))
        item2.append(everyTimeList)

    realPeriodExposure={}

    priceDict = {}
    realTimeOrder={}
    for item in item2:
        priceDict[item[1]]={}
        realPeriodExposure[item[1]]=0
        realTimeOrder[item[1]]=0
        if day == datetime.datetime.now().strftime("%Y-%m-%d"):
            if item[0] < nowTime<= item[1]:
                break
    for i in range(len(logs) - 1):
        if i==0:
            periodOrder=int(logs[i].realTimeOrder)
        else:
            periodOrder = int(logs[i + 1].realTimeOrder) - int(logs[i].realTimeOrder)
        periodExposure = int(logs[i + 1].exposureNum) - int(logs[i].exposureNum)
        for item in item2:
            if logs[i+1].biddingTime>item[0] and logs[i+1].biddingTime<=item[1]:
                if item[1] in priceDict.keys():
                    realPeriodExposure[item[1]]+=periodExposure
                    realTimeOrder[item[1]]+=periodOrder
                    if float(logs[i].basePrice) in priceDict[item[1]].keys():
                        priceDict[item[1]][float(logs[i].basePrice)]+=periodExposure
                    else:
                        priceDict[item[1]][float(logs[i].basePrice)] = periodExposure
                else:
                    realTimeOrder[item[1]]=periodOrder
                    realPeriodExposure[item[1]] = periodExposure
                    priceDict[item[1]][float(logs[i].basePrice)]=periodExposure
                break
    maxPrice = []
    minPrice = []
    avgPrice = []
    hourPriceCounts={}
    realTimeOrderList=[]
    for kDict,vDict in priceDict.items():
        if vDict=={}:
            maxPrice.append(0)
            minPrice.append(0)
            avgPrice.append(0)
            hourPriceCounts[kDict]=None
        else:
            pDict = sorted(vDict.items(), key=lambda x: x[0])
            minPrice.append(pDict[0][0])
            maxPrice.append(pDict[-1][0])
            allNum=0
            exposure=0
            price=[]
            priceNum=[]
            for t in pDict:
                t=list(t)
                if t[1]==0:
                    t[1]=1
                allNum+=t[0]*t[1]
                exposure+=t[1]
                price.append(t[0])
                priceNum.append(t[1])
            if int(exposure)==0:
                exposure=1
                allNum=0.1
            avgPrice.append(round(allNum/exposure,2))

    periodExposure=[]
    for k,v in realPeriodExposure.items():
            periodExposure.append(v)
    for k,v in realTimeOrder.items():
            realTimeOrderList.append(v)


    #处理小尾巴
    if periodExposure[-1] < 0:
        periodExposure[-1] = 0
    if realTimeOrderList[-1] < 0:
        realTimeOrderList[-1] = 0
    masterData={"maxPrice":maxPrice,"minPrice":minPrice,"avgPrice":avgPrice}
    item={"masterData":masterData,"periodExposure":periodExposure,
          "realTimeOrderList":realTimeOrderList}
    return item

def getIndexByTime(timestr):
    hour = int(timestr.split(":")[0])
    min = int(timestr.split(":")[1])
    if min > 30:
        index = hour * 2 + 1
    else:
        index = hour * 2
    return index


def reportCheck():
    session = Session()
    shops = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.deleted == 0).all()
    day = (datetime.datetime.now() + datetime.timedelta(days = -1)).strftime("%Y-%m-%d")
    checkResult = []
    for shop in shops:
        report = session.query(Report).filter(Report.shopId == shop.mtId, Report.date == day).first()
        if report:
            checkResult.append({"shopId":shop.mtId,"account":shop.account,"hasReportData":1, "shopName":shop.mtName})
        else:
            checkResult.append({"shopId": shop.mtId, "account": shop.account, "hasReportData": 0, "shopName":shop.mtName})

    return checkResult

def getYesReportData(shopId):

    session = Session()
    shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.mtId == shopId).first()
    shopName = shop.mtName
    try:
        cookies = shop.cookies
        shopId = shop.mtId

        k = 1
        day2 = (datetime.datetime.now() + datetime.timedelta(days=-1 * k)).strftime("%Y-%m-%d")
        endDay = day2.replace("-", '')

        label1 = -1
        label2 = -1
        labelData = getLabelData(cookies)
        if labelData[0]:
            label1 = labelData[0].get("nums")
        if labelData[1]:
            label2 = labelData[1].get("nums")

        repeatInfo = customerManageV3(shopId, 1, cookies)
        newOldInfo = get_customer_info(shopId, 1, cookies, endDay, endDay)[0]

        trendInfo = get_days_trend_info(shopId, 1, cookies)
        activityList = get_activity(shopId, 1, cookies)
        activityList = json.dumps(activityList, ensure_ascii=False)

        allRepeat = repeatInfo.get("allRepeat")
        allRepeatRate = repeatInfo.get("allRepeatRate")
        allRepeatCompareLastWeek = repeatInfo.get("allRepeatCompareLastWeek")
        allRepeatCompareLastMonth = repeatInfo.get("allRepeatCompareLastMonth")
        newRepeat = repeatInfo.get("newRepeat")
        newRepeatRate = repeatInfo.get("newRepeatRate")
        newRepeatCompareLastWeek = repeatInfo.get("newRepeatCompareLastWeek")
        newRepeatCompareLastMonth = repeatInfo.get("newRepeatCompareLastMonth")
        oldRepeat = repeatInfo.get("oldRepeat")
        oldRepeatRate = repeatInfo.get("oldRepeatRate")
        oldRepeatCompareLastWeek = repeatInfo.get("oldRepeatCompareLastWeek")
        oldRepeatCompareLastMonth = repeatInfo.get("oldRepeatCompareLastMonth")

        peerTrendInfo = get_peer_trend_info(shopId, 1, cookies)
        peerExposureNum = peerTrendInfo.get("peerExposureNum")
        peerVisitRate = peerTrendInfo.get("peerVisitRate")
        peerOrderRate = peerTrendInfo.get("peerOrderRate")

        overViewInfo = get_over_view(shopId, 1, cookies, endDay)
        cost = get_yes_cpc_info(shopId, 1, cookies)
        commentResult = get_comment(shopId, 1, cookies, day2, day2)
        commentList = commentResult.get("commentList")
        commentList = json.dumps(commentList, ensure_ascii=False)
        star = commentResult.get("star")
        star = json.dumps(star, ensure_ascii=False)
        exposureInfo = get_exposure_info(shopId, 1, cookies).get("exposureInfoList")
        bizListExposureNum = exposureInfo[0]
        searchExposureNum = exposureInfo[1]
        orderPageExposureNum = exposureInfo[2]
        selectForUExposureNum = exposureInfo[3]
        otherExposureNum = exposureInfo[4]
        peerExposureInfoList = get_exposure_info(shopId, 1, cookies).get("peerExposureInfoList")
        peerBizListExposureNum = peerExposureInfoList[0]
        peerSearchExposureNum = peerExposureInfoList[1]
        peerOrderPageExposureNum = peerExposureInfoList[2]
        peerSelectForUExposureNum = peerExposureInfoList[3]
        peerOtherExposureNum = peerExposureInfoList[4]

        score = get_comment_summary(shopId, 1, cookies)
        if not k == 1:
            bizListExposureNum = -1
            searchExposureNum = -1
            orderPageExposureNum = -1
            selectForUExposureNum = -1
            otherExposureNum = -1
            peerExposureNum = -1
            peerVisitRate = -1
            peerOrderRate = -1
            peerBizListExposureNum = -1
            peerSearchExposureNum = -1
            peerOrderPageExposureNum = -1
            peerSelectForUExposureNum = -1
            peerOtherExposureNum = -1
            cost = -1
        report = session.query(Report).filter(Report.date == day2, Report.shopId == shopId).first()
        if not report:
            session.add(Report(
                shopId=shopId,
                shopType=1,
                date=day2,
                comment=commentList,
                bizListExposureNum=bizListExposureNum,
                searchExposureNum=searchExposureNum,
                orderPageExposureNum=orderPageExposureNum,
                selectForUExposureNum=selectForUExposureNum,
                otherExposureNum=otherExposureNum,
                peerBizListExposureNum=peerBizListExposureNum,
                peerSearchExposureNum=peerSearchExposureNum,
                peerOrderPageExposureNum=peerOrderPageExposureNum,
                peerSelectForUExposureNum=peerSelectForUExposureNum,
                peerOtherExposureNum=peerOtherExposureNum,
                peerExposureNum=peerExposureNum,
                peerVisitRate=peerVisitRate,
                peerOrderRate=peerOrderRate,
                newSingle=newOldInfo.get("newSingle"),
                oldSingle=newOldInfo.get("oldSingle"),
                newPercent=newOldInfo.get("newPercent"),
                oldPercent=newOldInfo.get("oldPercent"),
                score=score,
                activity=activityList,
                exposureNum=trendInfo.get("exposureNum"),
                visitNum=trendInfo.get("visitNum"),
                orderNum=trendInfo.get("orderNum"),
                visitRate=trendInfo.get("visitRate"),
                orderRate=trendInfo.get("orderRate"),
                cost=cost,
                settleAcc=overViewInfo.get("settleAcc"),
                effectiveOrders=overViewInfo.get("effectiveOrders"),
                commentStarInfo=star,
                allRepeat=allRepeat,
                allRepeatRate=allRepeatRate,
                allRepeatCompareLastWeek=allRepeatCompareLastWeek,
                allRepeatCompareLastMonth=allRepeatCompareLastMonth,
                newRepeat=newRepeat,
                newRepeatRate=newRepeatRate,
                newRepeatCompareLastWeek=newRepeatCompareLastWeek,
                newRepeatCompareLastMonth=newRepeatCompareLastMonth,
                oldRepeat=oldRepeat,
                oldRepeatRate=oldRepeatRate,
                oldRepeatCompareLastWeek=oldRepeatCompareLastWeek,
                oldRepeatCompareLastMonth=oldRepeatCompareLastMonth,
                label1 = label1,
                label2 = label2,
            ))
        else:
            # 更新
            report.comment = commentList
            report.bizListExposureNum = bizListExposureNum
            report.searchExposureNum = searchExposureNum
            report.orderPageExposureNum = orderPageExposureNum
            report.selectForUExposureNum = selectForUExposureNum
            report.otherExposureNum = otherExposureNum
            report.newSingle = newOldInfo.get("newSingle")
            report.oldSingle = newOldInfo.get("oldSingle")
            report.newPercent = newOldInfo.get("newPercent")
            report.oldPercent = newOldInfo.get("oldPercent")
            report.score = score
            report.activity = activityList
            report.exposureNum = trendInfo.get("exposureNum")
            report.visitNum = trendInfo.get("visitNum")
            report.orderNum = trendInfo.get("orderNum")
            report.visitRate = trendInfo.get("visitRate")
            report.orderRate = trendInfo.get("orderRate")
            report.cost = cost
            report.settleAcc = overViewInfo.get("settleAcc")
            report.effectiveOrders = overViewInfo.get("effectiveOrders")
            report.commentStarInfo = star
            report.peerBizListExposureNum = peerBizListExposureNum
            report.peerSearchExposureNum = peerSearchExposureNum
            report.peerOrderPageExposureNum = peerOrderPageExposureNum
            report.peerSelectForUExposureNum = peerSelectForUExposureNum
            report.peerOtherExposureNum = peerOtherExposureNum
            report.peerExposureNum = peerExposureNum
            report.peerVisitRate = peerVisitRate
            report.peerOrderRate = peerOrderRate
            report.allRepeat = allRepeat
            report.allRepeatRate = allRepeatRate
            report.allRepeatCompareLastWeek = allRepeatCompareLastWeek
            report.allRepeatCompareLastMonth = allRepeatCompareLastMonth
            report.newRepeat = newRepeat
            report.newRepeatRate = newRepeatRate
            report.newRepeatCompareLastWeek = newRepeatCompareLastWeek
            report.newRepeatCompareLastMonth = newRepeatCompareLastMonth
            report.oldRepeat = oldRepeat
            report.oldRepeatRate = oldRepeatRate
            report.oldRepeatCompareLastWeek = oldRepeatCompareLastWeek
            report.oldRepeatCompareLastMonth = oldRepeatCompareLastMonth
            report.label1 = label1
            report.label2 = label2
    except:
        session.close()
        logger.info("{}：数据获取失败 =_=  =_=".format(shopName))
        logger.info(traceback.format_exc())
        return False
    session.commit()
    session.close()
    return True

def get_comment(shopId, shopType, cookies, startDay, endDay):
    if shopType == 1:
        commentList = []
        star = [0 for n in range(5)]
        mt = MTSpider(cookies)
        pageNum = 1
        commentCount = 1
        while True:
            res = mt.commentList(pageNum, startDay, endDay)
            comments = res.get("comments")
            if len(comments) == 0:
                break
            else:
                pageNum += 1
                for comment in comments:
                    clean_comment = comment.get("clean_comment")
                    add_comment = comment.get("add_comment")
                    starNum = comment.get("order_comment_score")
                    star[starNum - 1] += 1
                    if add_comment is None:
                        #将None转化为空字符串
                        add_comment = ''
                    if not clean_comment == '' or not add_comment == '':
                        #只要其中一个评论不为空
                        commentStr = str(commentCount) + "." + clean_comment + " " + add_comment
                        commentStr = emoji.demojize(commentStr)
                        commentList.append(commentStr)
                        commentCount += 1
        return {"commentList" : commentList, "star" : star}
def get_exposure_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.exposureInfo('1')
    flowExposureInfoList = res.get("flowExposureInfoList")
    # 01:商家列表； 02:搜索， 03:顾客订单页, 04:为你优选, 05:其他
    exposureInfoList = [0 for i in range(5)]
    peerExposureInfoList = [0 for i in range(5)]
    for flowExposureInfo in flowExposureInfoList:
        exposureInfoList[flowExposureInfo.get("entryId") - 1] = flowExposureInfo.get("exposureNum")
        peerExposureInfoList[flowExposureInfo.get("entryId") - 1] = flowExposureInfo.get("exposureNumTop")
    return {"exposureInfoList" : exposureInfoList, "peerExposureInfoList" : peerExposureInfoList }

def getLabelData(cookies):
    mt = MTSpider(cookies)

    yesterday = (datetime.datetime.now() + datetime.timedelta(days = -1)).strftime("%Y-%m-%d") + " 00:00:00"
    ta = time.strptime(yesterday, "%Y-%m-%d %H:%M:%S")
    ts = str(int(time.mktime(ta)))

    yesterday_end = (datetime.datetime.now()).strftime("%Y-%m-%d") + " 00:00:00"
    ta_end = time.strptime(yesterday_end, "%Y-%m-%d %H:%M:%S")
    ts_end = str(int(time.mktime(ta_end)))
    label1 = mt.checkLabel("2", ts, ts_end)  #进店未下单
    label2 = mt.checkLabel("3", ts, ts_end)  #下单未完成
    return [label1, label2]

def get_customer_info(shopId, shopType, cookies, startDay, endDay):
    mt = MTSpider(cookies)
    res = mt.customerManageV3NewOldView(1, startDay, endDay)
    newOldInfoList = []
    if res:
        newOldListIterator = res.get("newOldListIterator")
        for newOldInfo in newOldListIterator:
            dataDate = newOldInfo.get("dataDate")
            dataDate = dataDate[:4] + "-" + dataDate[4:6] + "-" + dataDate[6:]
            newSingle = newOldInfo.get("newSingle")
            oldSingle = newOldInfo.get("oldSingle")
            newPercent = newOldInfo.get("newPercent")
            oldPercent = newOldInfo.get("oldPercent")
            newOldInfoList.append({"dataDate" : dataDate, "newSingle" : newSingle, "oldSingle" : oldSingle, "newPercent" : newPercent, "oldPercent": oldPercent})
        return newOldInfoList
    else:
        newOldInfoList.append(
            {"dataDate": '', "newSingle": -1, "oldSingle": -1, "newPercent": -1,
             "oldPercent": -1})
        return newOldInfoList

def get_comment_summary(shopId, shopType, cookies):
    # 获取评分的接口
    mt = MTSpider(cookies)
    res = mt.commentSummary()
    bizScore = res.get("bizScore")
    return bizScore

def get_activity(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    activityList = []
    res = mt.getActivity("1,8", 1, 10)
    list = res.get("list")
    '''
        折扣商品: type:17
        满减：type:2
        店外领券：type:84
        减配送费: type: 25
        ...
    '''
    for activity in list:
        activityList.append({"name": activity.get("name"), "detail" : activity.get("detail"), "startTime":activity.get("startTime"), "endTime" : activity.get("endTime")})
    return activityList


def get_over_view(shopId, shopType, cookies, day):
    mt = MTSpider(cookies)
    res = mt.getHisOverView(day, day)
    settleAcc = res.get("settleAcc")
    effectiveOrders = res.get("effectiveOrders")
    return {"settleAcc": settleAcc, "effectiveOrders": effectiveOrders}

def customerManageV3(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.customerManageV3(2, '20190923' , '20191229')
    if res:
        allRepeat = res.get("allRepeat")
        allRepeatRate = res.get("allRepeatRate")
        allRepeatCompareLastWeek = res.get("allRepeatSequential")
        allRepeatCompareLastMonth = res.get("allRepeatCompareSame")

        newRepeat = res.get("newRepeat")
        newRepeatRate = res.get("newRepeatRate")
        newRepeatCompareLastWeek = res.get("newRepeatSequential")
        newRepeatCompareLastMonth = res.get("newRepeatCompareSame")

        oldRepeat = res.get("oldRepeat")
        oldRepeatRate = res.get("oldRepeatRate")
        oldRepeatCompareLastWeek = res.get("oldRepeatSequential")
        oldRepeatCompareLastMonth = res.get("oldRepeatCompareSame")

        return dict(
            allRepeat = allRepeat,
            allRepeatRate = allRepeatRate,
            allRepeatCompareLastWeek = allRepeatCompareLastWeek,
            allRepeatCompareLastMonth = allRepeatCompareLastMonth,
            newRepeat = newRepeat,
            newRepeatRate = newRepeatRate,
            newRepeatCompareLastWeek = newRepeatCompareLastWeek,
            newRepeatCompareLastMonth = newRepeatCompareLastMonth,
            oldRepeat = oldRepeat,
            oldRepeatRate = oldRepeatRate,
            oldRepeatCompareLastWeek = oldRepeatCompareLastWeek,
            oldRepeatCompareLastMonth = oldRepeatCompareLastMonth,
        )
    else:
        return dict(
            allRepeat=None,
            allRepeatRate=None,
            allRepeatCompareLastWeek=None,
            allRepeatCompareLastMonth=None,
            newRepeat=None,
            newRepeatRate=None,
            newRepeatCompareLastWeek=None,
            newRepeatCompareLastMonth=None,
            oldRepeat=None,
            oldRepeatRate=None,
            oldRepeatCompareLastWeek=None,
            oldRepeatCompareLastMonth=None,
        )

def get_trend_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getTrendList("1","1")
    '''
        曝光数，进店数，下单数
    '''
    flowChartsInfoList = res.get("flowChartsInfoList")
    exposureNum = flowChartsInfoList[-1].get("exposureNumLast")
    visitNum = flowChartsInfoList[-1].get("visitNumLast")
    orderNum = flowChartsInfoList[-1].get("orderNumLast")
    visitRate = flowChartsInfoList[-1].get("visitRateLast")
    orderRate = flowChartsInfoList[-1].get("orderRateLast")
    return {"exposureNum" : exposureNum, "visitNum" : visitNum, "orderNum" : orderNum, "visitRate" : visitRate, "orderRate" : orderRate}

def get_days_trend_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getTrendList("7","1")
    '''
        曝光数，进店数，下单数
    '''
    flowChartsInfoList = res.get("flowChartsInfoList")
    exposureNum = flowChartsInfoList[-1].get("exposureNum")
    visitNum = flowChartsInfoList[-1].get("visitNum")
    orderNum = flowChartsInfoList[-1].get("orderNum")
    visitRate = flowChartsInfoList[-1].get("visitRate")
    orderRate = flowChartsInfoList[-1].get("orderRate")
    return {"exposureNum" : exposureNum, "visitNum" : visitNum, "orderNum" : orderNum, "visitRate" : visitRate, "orderRate" : orderRate}

def get_peer_trend_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getOverView()
    flowOverviewInfo = res.get("data").get("flowOverviewInfo")
    peerExposureNum = flowOverviewInfo.get("exposureNumTop")
    peerVisitRate = flowOverviewInfo.get("visitRateTop")
    peerOrderRate = flowOverviewInfo.get("orderRateTop")
    return {"peerExposureNum" : peerExposureNum, "peerVisitRate" : peerVisitRate ,"peerOrderRate" : peerOrderRate}


def get_7days_trend_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    res = mt.getTrendList("7","1")
    trendInfoList = []
    '''
        曝光数，进店数，下单数
    '''
    flowChartsInfoList = res.get("flowChartsInfoList")
    for flowChartsInfo in flowChartsInfoList:
        exposureNum = flowChartsInfo.get("exposureNum")
        visitNum = flowChartsInfo.get("visitNum")
        orderNum = flowChartsInfo.get("orderNum")
        visitRate = flowChartsInfo.get("visitRate")
        orderRate = flowChartsInfo.get("orderRate")
        date = flowChartsInfo.get("date")
        peerExposureNum = flowChartsInfo.get("exposureNumTop")
        peerVisitRate = flowChartsInfo.get("visitRateTop")
        peerOrderRate = flowChartsInfo.get("orderRateTop")
        trendInfoList.append({"date" : date,"peerExposureNum":peerExposureNum,"peerVisitRate":peerVisitRate,"peerOrderRate":peerOrderRate,  "exposureNum" : exposureNum, "visitNum" : visitNum, "orderNum" : orderNum, "visitRate" : visitRate, "orderRate" : orderRate})
    return trendInfoList


def get_yes_cpc_info(shopId, shopType, cookies):
    mt = MTSpider(cookies)
    cpcInfo = mt.gettodayExposure()
    cost = cpcInfo.get("data").get("yesterdayOverview").get("cost")
    return cost

def upd_operation(operationDaily):
    """
    更新日志到数据库
    :param operationDaily:
    :return:
    """
    session = Session()
    try:
        if not isinstance(operationDaily,list):
            session.add(operationDaily)
        else:
            session.add_all(operationDaily)
        session.commit()
        session.close()
    except:
        session.close()
        session.rollback()
        return True

def upd_oprt_daily(request_path, request_param):
    """
    将操作日志更新到数据库中
    :param request_path:
    :param request_param:
    :return:
    """
    errlog = ''
    shopId = request_param.get("shopId")
    shopType = int(request_param.get("shopType"))
    if len(shopId) > 15:
        shopId = decryptShopId(shopId, shopType)
        if shopId == 1000:
            errlog = "解密shopId错误！"
            logger.info("解密shopId错误！"+str(shopId))
    type = 1
    now_day = datetime.datetime.now()
    operationDaily = OperationDaily(
        shopId=shopId,
        type=type,
        day=now_day.strftime("%Y-%m-%d"),
        createTime=now_day.strftime("%Y-%m-%d %H:%M:%S"),
        params=str(request_param),
        errorLog=errlog,
        account="",
        apiName=request_path,
        remark="",
    )
    upd_operation(operationDaily)

def getResearchData():
    session = SessionResearch()
    researchData = session.query(Research).all()
    result = []
    for research in researchData:
        result.append(
            {"user_id" : research.user_id,
             "location_xy" : research.location_xy,
             "location_name" : research.location_name,
             "num" : research.num,
             "category_name" : research.category_name,
             "category_code" : research.category_code}
        )
    return result

def getBiddingDateFromOpet(shopid):
    """
    获取shopid店铺的所有接口操作日志
    :param shopid:
    :param status: 智能推广 0：100   定时定价 1：010  手动推广 2：001
    :return:
    """
    session = Session()
    try:
        opet_daily = session.query(OperationDaily).filter(OperationDaily.shopId == shopid, OperationDaily.apiName == '/api/v1/chart/shop/setStatus').all()
        session.close()
        return opet_daily
    except:
        session.rollback()
        session.close()
        return False

def getDate(shopid):
    # 获取这个店铺所有的操作记录
    opet_daily = getBiddingDateFromOpet(shopid)
    for op_da in opet_daily:
        op_da = op_da.to_dict()
        params = eval(op_da.get("params"))
        status2 = int(params.get("status2"))
        status3 = int(params.get("status3"))
        status4 = int(params.get("status4"))
        if status2 == 1 and status3 == 0 and status4 == 0:
            date = op_da.get("day")
            return date


def getBiddingsData(shopid):
    """
    获取竞价系统店铺的运营效果
    :param shopid:
    :return:
    """
    # 开始推广的时间
    date = str(getDate(shopid))
    # 获取推广的所有需要的数据
    busi_list, head_list = getBiddingData(shopid)
    # 对数据进行划分，分为智能推广之前的数据，以及智能推广之后的数据，先对busi_list的数据进行划分
    previous_list = []
    later_list = []
    for b_list in busi_list:
        if b_list.get("day") < date:
            previous_list.append(b_list)
        else:
            later_list.append(b_list)
    # 处理headInfo中的数据
    busi_list_lat_day = str(busi_list[-1].get("day"))
    for h_list in head_list:
        if h_list.get("day") > busi_list_lat_day:
            if h_list.get("day") < date:
                previous_list.append(h_list)
            else:
                later_list.append(h_list)
    # 获得数据之后，进行数据比对
    # for循环遍历智能推广的数据，并且获取准备数据分析需要的集合
    lenth_later_list = len(later_list)
    # 近七天以及近十天开始时间
    pre_start_time = datetime.datetime.strptime(str(date), "%Y-%m-%d")
    pre_start_time_strday = pre_start_time.strftime("%Y-%m-%d")
    # 近七天的数据的结束时间
    pre_end_seven_time = pre_start_time + datetime.timedelta(days=6)
    pre_end_seven_time_strday = pre_end_seven_time.strftime("%Y-%m-%d")
    # 近十天的数据的结束时间
    pre_end_ten_time = pre_start_time + datetime.timedelta(days=9)
    pre_end_ten_time_strday = pre_end_ten_time.strftime("%Y-%m-%d")
    # 智能推广的结束时间
    pre_lately_end_time = datetime.datetime.now()
    pre_lately_end_time_strday = pre_lately_end_time.strftime("%Y-%m-%d")
    # 智能推广后的七天的数据
    pre_lately_end_seven_time = pre_lately_end_time + datetime.timedelta(days=-6)
    pre_lately_end_seven_time_strday = pre_lately_end_seven_time.strftime("%Y-%m-%d")
    # 智能推广后的十天的数据
    pre_lately_end_ten_time = pre_lately_end_time + datetime.timedelta(days=-9)
    pre_lately_end_ten_time_strday = pre_lately_end_ten_time.strftime("%Y-%m-%d")
    # 当前自然周的数据
    week_now = datetime.datetime.now().weekday()
    # 自然周的数据的开始结束时间
    one_end_week_time = datetime.datetime.now()
    one_end_week_time_strday = one_end_week_time.strftime("%Y-%m-%d")
    one_start_week_time = one_end_week_time + datetime.timedelta(days=-int(week_now))
    one_start_week_time_strday = one_start_week_time.strftime("%Y-%m-%d")
    # now_week_day = []
    # for i in range(0,lenth_later_list):
    #     mid_week_day = later_list[lenth_later_list-i-1]
    #     now_week_day.append(mid_week_day)
    #     if mid_week_day.get("week")==0:
    #         break

    # 获取智能推广之前的数据，并且获取准备数据分析需要的集合
    lenth_pre_list = len(previous_list)
    # 计算最近七天的数据
    # 所有的开始时间
    start_one_time = (datetime.datetime.strptime(str(date), "%Y-%m-%d") + datetime.timedelta(days=-1))
    start_one_time_strday = start_one_time.strftime("%Y-%m-%d")
    # 第一个结束的时间
    end_seven_one_time = start_one_time + datetime.timedelta(days=-6)
    end_seven_one_time_strday = end_seven_one_time.strftime("%Y-%m-%d")
    # 第二个结束时间
    end_seven_two_time = end_seven_one_time + datetime.timedelta(days=-7)
    end_seven_two_time_strday = end_seven_two_time.strftime("%Y-%m-%d")
    # 第三个结束时间
    end_seven_three_time = end_seven_two_time + datetime.timedelta(days=-7)
    end_seven_three_time_strday = end_seven_three_time.strftime("%Y-%m-%d")
    # 第四个结束时间
    end_seven_four_time = end_seven_three_time + datetime.timedelta(days=-7)
    end_seven_four_time_strday = end_seven_four_time.strftime("%Y-%m-%d")
    # 十天类型的数据集合
    end_ten_one_time = start_one_time + datetime.timedelta(days=-9)
    end_ten_one_time_strday = end_ten_one_time.strftime("%Y-%m-%d")
    end_ten_two_time = end_seven_one_time + datetime.timedelta(days=-10)
    end_ten_two_time_strday = end_ten_two_time.strftime("%Y-%m-%d")
    end_ten_three_time = end_seven_two_time + datetime.timedelta(days=-10)
    end_ten_three_time_strday = end_ten_three_time.strftime("%Y-%m-%d")
    # 自然周数据获取
    pre_now_week_day = None
    for i in range(0, lenth_pre_list):
        num = previous_list[lenth_pre_list - i - 1].get("week")
        if num == week_now:
            pre_now_week_day = previous_list[lenth_pre_list - i - 1].get("day")
            break
    # 智能推广之前的第一个自然周的数据
    pre_start_one_week_time = datetime.datetime.strptime(str(pre_now_week_day), "%Y-%m-%d")
    pre_start_one_week_time_strday = pre_start_one_week_time.strftime("%Y-%m-%d")
    pre_end_one_week_time = pre_start_one_week_time + datetime.timedelta(days=-int(week_now))
    pre_end_one_week_time_strday = pre_end_one_week_time.strftime("%Y-%m-%d")
    # 智能推广之前的第二个自然周的数据
    pre_start_two_week_time = pre_start_one_week_time + datetime.timedelta(days=-7)
    pre_start_two_week_time_strday = pre_start_two_week_time.strftime("%Y-%m-%d")
    pre_end_two_week_time = pre_end_one_week_time + datetime.timedelta(days=-7)
    pre_end_two_week_time_strday = pre_end_two_week_time.strftime("%Y-%m-%d")
    # 智能推广之前的第三个自然周的数据
    pre_start_three_week_time = pre_start_two_week_time + datetime.timedelta(days=-7)
    pre_start_three_week_time_strday = pre_start_three_week_time.strftime("%Y-%m-%d")
    pre_end_three_week_time = pre_end_two_week_time + datetime.timedelta(days=-7)
    pre_end_three_week_time_strday = pre_end_three_week_time.strftime("%Y-%m-%d")
    # 智能推广之前的第二个自然周的数据
    pre_start_four_week_time = pre_start_three_week_time + datetime.timedelta(days=-7)
    pre_start_four_week_time_strday = pre_start_four_week_time.strftime("%Y-%m-%d")
    pre_end_four_week_time = pre_end_three_week_time + datetime.timedelta(days=-7)
    pre_end_four_week_time_strday = pre_end_four_week_time.strftime("%Y-%m-%d")

    # 先前数据的所有维度的列表
    # 七天的四个列表
    one_seven_day_list = []
    two_seven_day_list = []
    three_seven_day_list = []
    four_seven_day_list = []
    # 十天的四个列表
    one_ten_day_list = []
    two_ten_day_list = []
    three_ten_day_list = []
    four_ten_day_list = []
    # 四个自然周的数据
    one_week_day_list = []
    two_week_day_list = []
    three_week_day_list = []
    four_week_day_list = []
    for pre in previous_list:
        pre_day = str(pre.get("day"))
        # 一七天
        if pre_day >= end_seven_one_time_strday and pre_day <= start_one_time_strday:
            one_seven_day_list.append(pre)
        # 二七天
        if pre_day >= end_seven_two_time_strday and pre_day <= start_one_time_strday:
            two_seven_day_list.append(pre)
        # 三七天
        if pre_day >= end_seven_three_time_strday and pre_day <= start_one_time_strday:
            three_seven_day_list.append(pre)
        # 四七天
        if pre_day >= end_seven_four_time_strday and pre_day <= start_one_time_strday:
            four_seven_day_list.append(pre)
            # 一十天
        if pre_day >= end_ten_one_time_strday and pre_day <= start_one_time_strday:
            one_ten_day_list.append(pre)
            # 二十天
        if pre_day >= end_ten_two_time_strday and pre_day <= start_one_time_strday:
            two_ten_day_list.append(pre)
            # 三十天
        if pre_day >= end_ten_three_time_strday and pre_day <= start_one_time_strday:
            three_ten_day_list.append(pre)
        # 第一个自然周
        if pre_day >= pre_end_one_week_time_strday and pre_day <= pre_start_one_week_time_strday:
            one_week_day_list.append(pre)
        # 第二个自然周
        if pre_day >= pre_end_two_week_time_strday and pre_day <= pre_start_two_week_time_strday:
            two_week_day_list.append(pre)
        # 第三个自然周
        if pre_day >= pre_end_three_week_time_strday and pre_day <= pre_start_three_week_time_strday:
            three_week_day_list.append(pre)
        # 第四个自然周
        if pre_day >= pre_end_four_week_time_strday and pre_day <= pre_start_four_week_time_strday:
            four_week_day_list.append(pre)

    # 智能推广之后的数据
    # 近七天的列表
    later_last_seven_list = []
    # 开始七天的列表
    later_begin_seven_list = []
    # 近十天的列表
    later_last_ten_list = []
    # 开始十天的列表
    later_begin_ten_list = []
    # 自然周的列表
    later_week_list = []
    for lat in later_list:
        later_day = str(lat.get("day"))
        # 近七天的列表
        if later_day >= pre_start_time_strday and later_day <= pre_end_seven_time_strday:
            later_last_seven_list.append(lat)
        # 开始七天的列表
        if later_day >= pre_lately_end_seven_time_strday  and later_day <= pre_lately_end_time_strday:
            later_begin_seven_list.append(lat)
        # 近十天的列表
        if later_day >= pre_start_time_strday and later_day <= pre_end_ten_time_strday:
            later_last_ten_list.append(lat)
        # 开始十天的列表
        if later_day >= pre_lately_end_ten_time_strday and later_day <= pre_lately_end_time_strday:
            later_begin_ten_list.append(lat)
        # 自然周的列表
        if later_day <= one_end_week_time_strday and later_day >= one_start_week_time_strday:
            later_week_list.append(lat)

    # 先前数据的所有维度的列表
    # 七天的四个列表
    one_seven_day_list_result = getAvgByList(one_seven_day_list)
    two_seven_day_list_result = getAvgByList(two_seven_day_list)
    three_seven_day_list_result = getAvgByList(three_seven_day_list)
    four_seven_day_list_result = getAvgByList(four_seven_day_list)
    # 十天的四个列表
    one_ten_day_list_result = getAvgByList(one_ten_day_list)
    two_ten_day_list_result = getAvgByList(two_ten_day_list)
    three_ten_day_list_result = getAvgByList(three_ten_day_list)
    four_ten_day_list_result = getAvgByList(four_ten_day_list)
    # 四个自然周的数据
    one_week_day_list_result = getAvgByList(one_week_day_list)
    two_week_day_list_result = getAvgByList(two_week_day_list)
    three_week_day_list_result = getAvgByList(three_week_day_list)
    four_week_day_list_result = getAvgByList(four_week_day_list)

    # 智能推广之后的数据
    # 近七天的列表
    later_last_seven_list_result = getAvgByList(later_last_seven_list)
    # 开始七天的列表
    later_begin_seven_list_result = getAvgByList(later_begin_seven_list)
    # 近十天的列表
    later_last_ten_list_result = getAvgByList(later_last_ten_list)
    # 开始十天的列表
    later_begin_ten_list_result = getAvgByList(later_begin_ten_list)
    # 自然周的列表
    later_week_list_result = getAvgByList(later_week_list)

    # 二十种对比情况，排列组合依次列出，数据格式为{"later":[] ,"pre":[], "cha":[]}
    back_data = [{"later": later_last_seven_list_result, "pre": one_seven_day_list_result,
                  "cha": [later_last_seven_list_result[i] - one_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "近七天和第一个七天对比"},
                 {"later": later_last_seven_list_result, "pre": two_seven_day_list_result,
                  "cha": [later_last_seven_list_result[i] - two_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "近七天和第二个七天对比"},
                 {"later": later_last_seven_list_result, "pre": three_seven_day_list_result,
                  "cha": [later_last_seven_list_result[i] - three_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "近七天和第三个七天对比"},
                 {"later": later_last_seven_list_result, "pre": four_seven_day_list_result,
                  "cha": [later_last_seven_list_result[i] - four_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "近七天和第四个七天对比"},
                 {"later": later_begin_seven_list_result, "pre": one_seven_day_list_result,
                  "cha": [later_begin_seven_list_result[i] - one_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "开始七天和第一个七天对比"},
                 {"later": later_begin_seven_list_result, "pre": two_seven_day_list_result,
                  "cha": [later_begin_seven_list_result[i] - two_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "开始七天和第二个七天对比"},
                 {"later": later_begin_seven_list_result, "pre": three_seven_day_list_result,
                  "cha": [later_begin_seven_list_result[i] - three_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "开始七天和第三个七天对比"},
                 {"later": later_begin_seven_list_result, "pre": four_seven_day_list_result,
                  "cha": [later_begin_seven_list_result[i] - four_seven_day_list_result[i] for i in range(0, 2)],
                  "log": "开始七天和第四个七天对比"},
                 {"later": later_last_ten_list_result, "pre": one_ten_day_list_result,
                  "cha": [later_last_ten_list_result[i] - one_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "近十天和第一个十天对比"},
                 {"later": later_last_ten_list_result, "pre": two_ten_day_list_result,
                  "cha": [later_last_ten_list_result[i] - two_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "近十天和第二个十天对比"},
                 {"later": later_last_ten_list_result, "pre": three_ten_day_list_result,
                  "cha": [later_last_ten_list_result[i] - three_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "近十天和第三个十天对比"},
                 {"later": later_begin_ten_list_result, "pre": one_ten_day_list_result,
                  "cha": [later_begin_ten_list_result[i] - one_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "开始十天和第一个十天对比"},
                 {"later": later_begin_ten_list_result, "pre": two_ten_day_list_result,
                  "cha": [later_begin_ten_list_result[i] - two_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "开始十天和第二个十天对比"},
                 {"later": later_begin_ten_list_result, "pre": three_ten_day_list_result,
                  "cha": [later_begin_ten_list_result[i] - three_ten_day_list_result[i] for i in range(0, 2)],
                  "log": "开始十天和第三个十天对比"},
                 {"later": later_week_list_result, "pre": one_week_day_list_result,
                  "cha": [later_week_list_result[i] - one_week_day_list_result[i] for i in range(0, 2)],
                  "log": "当前自然周于与第一个自然周比较"},
                 {"later": later_week_list_result, "pre": two_week_day_list_result,
                  "cha": [later_week_list_result[i] - two_week_day_list_result[i] for i in range(0, 2)],
                  "log": "当前自然周于与第二个自然周比较"},
                 {"later": later_week_list_result, "pre": three_week_day_list_result,
                  "cha": [later_week_list_result[i] - three_week_day_list_result[i] for i in range(0, 2)],
                  "log": "当前自然周于与第三个自然周比较"},
                 {"later": later_week_list_result, "pre": four_week_day_list_result,
                  "cha": [later_week_list_result[i] - four_week_day_list_result[i] for i in range(0, 2)],
                  "log": "当前自然周于与第四个自然周比较"}, ]
    return back_data

def getAvgByList(l_list):
    """
    获取列表中各项数据的平均值，以及比值
    :param l_list:
    :return:
    """
    lenth = len(l_list)
    all_cost = 0
    all_exposureNum = 0
    all_clickNum = 0
    for l in l_list:
        all_cost += float(l.get("cost"))
        all_exposureNum += float(l.get("exposureNum"))
        all_clickNum += float(l.get("clickNum"))
    if not (all_clickNum and all_cost):
        return [0,0]
    ep_cost = round(all_exposureNum / all_cost,4)
    cost_click = round(all_cost / all_clickNum,4)
    # ep_cost = all_exposureNum / all_cost
    # cost_click = all_cost / all_clickNum
    return [ep_cost,cost_click]

def getHeadInfoData(shopid):
    """
    获取当前账号的所有的headInfo
    :param shopid:
    :return:
    """
    session = Session()
    try:
        account = session.query(ShopMeituanInfo.account).filter(ShopMeituanInfo.mtId == shopid).first()[0]
        headInfos = session.query(YesOrderInfo.headInfo, YesOrderInfo.day).filter(YesOrderInfo.account == account).all()
        session.close()
        return headInfos
    except:
        session.rollback()
        session.close()
        return False


def getBusinessInfo(shopid):
    """
    获取该店铺的所有录店之前的运营数据
    :param shopid:
    :return:
    """
    session = Session()
    try:
        business_infos = session.query(BusinessInfo).filter(BusinessInfo.shopId == shopid).all()
        session.close()
        return business_infos
    except:
        session.rollback()
        session.close()
        return False

def getBiddingData(shopid):
    #获取推广之前和推广之后的数据
    # headInfo中获取
    head_info_data = getHeadInfoData(shopid)
    # business_info中获取
    business_info = getBusinessInfo(shopid)
    #将所有的数据进行去重，以及进行格式上的统一
    #必须要有的数据有：每天的花费，当天的曝光，当天的访客数（以后需要的时候再进行获取，入店转化率，下单转化率等信息）
    busi_list = []
    head_list = []
    for b_info in business_info:
        if b_info.cost != 0:
            week = datetime.datetime.strptime(str(b_info.day), "%Y-%m-%d").weekday()
            busi_list.append({"cost":b_info.cost, "exposureNum": b_info.exposureNum, "clickNum": b_info.clickNum, "day": str(b_info.day), "week":week})
    for h_info in head_info_data:
        if h_info.headInfo:
            head_info = eval(h_info.headInfo)
            cost = float(head_info.get("cot").get("p"))
            exposureNum = int(head_info.get("ep").get("o"))
            clickNum = (head_info.get("ck").get("o"))
            if cost and exposureNum and clickNum:
                day = h_info.day
                week = datetime.datetime.strptime(str(day), "%Y-%m-%d").weekday()
                head_list.append({"cost":cost, "exposureNum": exposureNum, "clickNum": clickNum, "day": str(day), "week":week})
    return busi_list,head_list

def saveAllExposureRate(account, shopType, updExposureRate):
    session = Session()

    if shopType == 1:
        shop = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == account).first()
    else:
        shop = session.query(ShopEleInfo).filter(ShopEleInfo.account == account).first()

    shop.shopTimeStart = str(updExposureRate)
    session.commit()
    session.close()


def getNextExposureRate(account,shopType):
    session = Session()
    if shopType == 1:
        plan = session.query(ShopMeituanInfo.plan).filter(ShopMeituanInfo.account == account).scalar()
    else:
        plan = session.query(ShopEleInfo.plan).filter(ShopEleInfo.account == account).scalar()

    if plan:
        plan = eval(plan)
        if plan.get("nextExposureRate",None):
            return float(plan.get("nextExposureRate"))
        else:
            return 1
    else:
        return 1


def getExposureRate(account, shopId, shopType, budget, adTime, targetexposure,controlRate,baseRate):
    nowTime = (datetime.datetime.now()).strftime("%H:%M")
    nowTime_add = (datetime.datetime.now() + datetime.timedelta(minutes=-1)).strftime("%H:%M")
    nowDay = (datetime.datetime.now()).strftime("%Y-%m-%d")

    session = Session()
    shopBidding = session.query(ShopBidding).filter(ShopBidding.shopid == shopId, ShopBidding.biddingTime >= nowDay + " 00:00:00",
                                                    ShopBidding.shoptype == shopType, ).order_by(
        ShopBidding.id.desc()).first()

    currentCost = shopBidding.currentCost
    currentBudget = session.query(ShopBiddingTarget.budget).filter(ShopBiddingTarget.account == account,
                                                                   or_(
                                                                       ShopBiddingTarget.exposureTime == nowDay + " " + nowTime + ":00",
                                                                       ShopBiddingTarget.exposureTime == nowDay + " " + nowTime_add + ":00")).scalar()

    if not currentBudget:
        return -200
    realRemaindingBudget = float(budget) - float(currentCost)
    if realRemaindingBudget > 0:
        shouldRemaindingBudget = float(budget) - float(currentBudget)
        if abs(realRemaindingBudget - shouldRemaindingBudget) / shouldRemaindingBudget > controlRate:
            rate = (float(budget) - float(currentCost)) / (float(budget) - float(currentBudget)) * baseRate
            rate = round(rate,3)
        else:
            rate = -99

        return rate
    return -99

def checkBuckupIp():
    session = Session2()
    ips = session.query(IpPool).all()
    spareIp = []
    usingIp = []
    invalidIp = []
    testResult = []
    for ip in ips:
        if ip.valid == 1:
            usingIp.append(ip.ip)
        elif ip.valid == 2:
            invalidIp.append(ip.ip)
        else:
            spareIp.append(ip.ip)
            testResult.append(-1)
    return {"spareIp":spareIp,"usingIp":usingIp,"invalidIp":invalidIp,"testResult":testResult,"spareIpNum":len(spareIp),"usingIpNum":len(usingIp),"invalidIpNum":len(invalidIp)}


def changeNewIp(ips):
    try:
        session = Session()
        shops = session.query(ShopMeituanInfo).all()
        i = 0
        for shop in shops:
            ip = str(ips[i % len(ips)])
            shopOne = session.query(ShopMeituanInfo).filter(ShopMeituanInfo.account == shop.account).first()
            shopOne.ip = ip
            i = i + 1
        session.commit()

        return True
    except:
        logger.info(traceback.format_exc())
        return False
    finally:
        session.close()
